Skip to main content
 首页 » 编程设计

python之将 (nx2) 个 float 组转换为 (nx1) 个二元组数组

2025年05月04日13lyj

我有一个 NumPy float 组

x = np.array([ 
    [0.0, 1.0], 
    [2.0, 3.0], 
    [4.0, 5.0] 
    ], 
    dtype=np.float32 
    ) 

并且需要将其转换为具有元组数据类型的 NumPy 数组,

y = np.array([ 
    (0.0, 1.0), 
    (2.0, 3.0), 
    (4.0, 5.0) 
    ], 
    dtype=np.dtype((np.float32, 2)) 
    ) 

NumPy view很遗憾,我们在这里不工作:

y = x.view(dtype=np.dtype((np.float32, 2))) 
ValueError: new type not compatible with array. 

是否有机会在不遍历 x 并复制每个条目的情况下完成此操作?

请您参考如下方法:

这很接近:

In [122]: dt=np.dtype([('x',float,(2,))]) 
 
In [123]: y=np.zeros(x.shape[0],dtype=dt) 
 
In [124]: y 
Out[124]:  
array([([0.0, 0.0],), ([0.0, 0.0],), ([0.0, 0.0],)],  
      dtype=[('x', '<f8', (2,))]) 
 
In [125]: y['x']=x 
 
In [126]: y 
Out[126]:  
array([([0.0, 1.0],), ([2.0, 3.0],), ([4.0, 5.0],)],  
      dtype=[('x', '<f8', (2,))]) 
 
In [127]: y['x'] 
Out[127]:  
array([[ 0.,  1.], 
       [ 2.,  3.], 
       [ 4.,  5.]]) 

y 有一个复合字段。该字段有 2 个元素。

或者,您可以定义 2 个字段:

In [134]: dt=np.dtype('f,f') 
In [135]: x.view(dt) 
Out[135]:  
array([[(0.0, 1.0)], 
       [(2.0, 3.0)], 
       [(4.0, 5.0)]],  
      dtype=[('f0', '<f4'), ('f1', '<f4')]) 

但那是形状(3,1);所以 reshape :

In [137]: x.view(dt).reshape(3) 
Out[137]:  
array([(0.0, 1.0), (2.0, 3.0), (4.0, 5.0)],  
      dtype=[('f0', '<f4'), ('f1', '<f4')]) 

除了显示与您的 y 相同的 dtype。