我正在使用Python 2.7中的Numpy 1.6,并从另一个模块获取一些1D数组。我希望将这些数组打包成结构化数组,以便可以通过名称索引原始1D数组。我无法弄清楚如何将1D数组转换为2D数组并使dtype访问正确的数据。我的最小工作示例如下:
>>> import numpy as np
>>>
>>> x = np.random.randint(10,size=3)
>>> y = np.random.randint(10,size=3)
>>> z = np.random.randint(10,size=3)
>>> x
array([9, 4, 7])
>>> y
array([5, 8, 0])
>>> z
array([2, 3, 6])
>>>
>>> w = np.array([x,y,z])
>>> w.dtype=[('x','i4'),('y','i4'),('z','i4')]
>>> w
array([[(9, 4, 7)],
[(5, 8, 0)],
[(2, 3, 6)]],
dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])
>>> w['x']
array([[9],
[5],
[2]])
>>>
>>> u = np.vstack((x,y,z))
>>> u.dtype=[('x','i4'),('y','i4'),('z','i4')]
>>> u
array([[(9, 4, 7)],
[(5, 8, 0)],
[(2, 3, 6)]],
dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])
>>> u['x']
array([[9],
[5],
[2]])
>>> v = np.column_stack((x,y,z))
>>> v
array([[(9, 4, 7), (5, 8, 0), (2, 3, 6)]],
dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])
>>> v.dtype=[('x','i4'),('y','i4'),('z','i4')]
>>> v['x']
array([[9, 5, 2]])
正如您所看到的,尽管我的原始 x
数组包含 [9,4,7]
,但我尝试堆叠数组并按 'x'
索引返回的结果都与原始的 x
数组不同。有没有办法实现这一点,或者我的方法存在问题?