将 (nx2) 个浮点数组转换为 (nx1) 个二元组数组

convert (nx2) array of floats into (nx1) array of 2-tuples

我有一个 NumPy 浮点数组

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 views 很遗憾不能在这里工作:

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);所以重塑:

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 之外。