本文介绍了numpy将一维数组堆叠到结构化数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python 2.7中运行Numpy 1.6,并且有一些我从另一个模块获取的一维数组.我想将这些数组打包成结构化数组,以便按名称索引原始一维数组.我在弄清楚如何将1D数组转换为2D数组并使dtype访问正确的数据时遇到了麻烦.我的MWE如下:

I'm running Numpy 1.6 in Python 2.7, and have some 1D arrays I'm getting from another module. I would like to take these arrays and pack them into a structured array so I can index the original 1D arrays by name. I am having trouble figuring out how to get the 1D arrays into a 2D array and make the dtype access the right data. My MWE is as follows:

>>> 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数组.有办法做到这一点,还是我做错了?

As you can see, while my original x array contains [9,4,7], no way I've attempted to stack the arrays and then index by 'x' returns the original x array. Is there a way to do this, or am I coming at it wrong?

推荐答案

一种方法是

wtype=np.dtype([('x',x.dtype),('y',y.dtype),('z',z.dtype)])
w=np.empty(len(x),dtype=wtype)
w['x']=x
w['y']=y
w['z']=z

请注意,randint返回的每个数字的大小取决于您的平台,因此在我的计算机上,我使用的是int64而不是int32,即"i4".另一种方法更可移植.

Notice that the size of each number returned by randint depends on your platform, so instead of an int32, i.e. 'i4', on my machine I have an int64 which is 'i8'. This other way is more portable.

这篇关于numpy将一维数组堆叠到结构化数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:11
查看更多