2013-07-03 89 views
4

我在Python 2.7中运行Numpy 1.6,并且从一个模块中获得了一些1D数组。我想采取这些数组并将它们打包到一个结构化数组中,这样我就可以按名称对原始1D数组进行索引。我无法弄清楚如何将一维数组转换为二维数组,并使dtype访问正确的数据。我MWE如下:numpy将1D数组堆叠到结构化数组中

>>> 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阵列堆叠阵列,然后索引。有没有办法做到这一点,或者我错了吗?

+0

你需要在2d阵列上操作吗?为什么不使用字典? – OregonTrail

+0

我想我只是假设不混合数据类型并使用ndarray会更好,因为它支持字典索引,但是没有真正的推理。 – Thav

+0

要回答第一个问题,不,在这种情况下,我不需要在2d阵列上操作。 – Thav

回答

6

一条路可走是

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返回的大小取决于你的平台上,所以不是一个Int32,即“6-14”,我的机器上我有一个Int64这是'i8'。这另一种方式更便携。

+3

+1这实际上是将具有不同dtype的数组放入单个结构化数组的唯一方法。 – Jaime

0

使用字典

#!/usr/bin/env python 

import numpy 

w = {} 
for key in ('x', 'y', 'z'): 
    w[key] = np.random.randint(10, size=3) 

print w 
3

你想用np.column_stack

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) 

w = np.column_stack((x, y, z)) 
w = w.ravel().view([('x', x.dtype), ('y', y.dtype), ('z', z.dtype)]) 

>>> w 
array([(5, 1, 8), (8, 4, 9), (4, 2, 6)], 
     dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) 
>>> x 
array([5, 8, 4]) 
>>> y 
array([1, 4, 2]) 
>>> z 
array([8, 9, 6]) 
>>> w['x'] 
array([5, 8, 4]) 
>>> w['y'] 
array([1, 4, 2]) 
>>> w['z'] 
array([8, 9, 6]) 
+0

我在我的例子中使用了'column_stack',但没有得到和你一样的结果。我猜想不同之处在'w.rave1()...'行,但我不太明白那里发生了什么。 – Thav

+1

如果1D阵列的数据类型占用不同数量的字节,则会失败。 –

1

你可能要考虑numpy的纪录阵列用于该用途:

“numpy的提供了强大的功能,创建结构或记录数组,这些数组允许通过结构体或结构体的字段来处理数据。“

这里有记录阵列文档: http://docs.scipy.org/doc/numpy/user/basics.rec.html

您可以使用您的变量名作为字段名。