2013-07-03 91 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

您可以使用您的變量名作爲字段名。