2013-10-17 41 views
2

我可以創建一個recarray並通過名稱來訪問它的成員:如何訪問numpy recarray的字段#k?

import numpy as np 

n = 20 
x = np.recarray((n,), dtype=[('x',int),('y',float),('label',object)]) 
x.x[:] = range(n) 
x.y[:] = np.arange(n)*0.08 
x.label[:] = ['%d bottles of beer on the wall' % i for i in range(n)] 

,我可以通過行索引訪問數據,或者遍歷行:

>>> print x[3] 
(3, 0.24, '3 bottles of beer on the wall') 

但我怎麼能遍歷在領域或得到k th字段在recarray?

+0

嗯。我將從'numpy.recarray'切換到'pandas.DataFrame'。 –

回答

3

recarray s有一個field()方法爲此目的。用你的例子...

>>> x.field(2) 
... array(['0 bottles of beer on the wall', '1 bottles of beer on the wall', 
     '2 bottles of beer on the wall', '3 bottles of beer on the wall', 
     '4 bottles of beer on the wall', '5 bottles of beer on the wall', 
     '6 bottles of beer on the wall', '7 bottles of beer on the wall', 
     '8 bottles of beer on the wall', '9 bottles of beer on the wall', 
     '10 bottles of beer on the wall', '11 bottles of beer on the wall', 
     '12 bottles of beer on the wall', '13 bottles of beer on the wall', 
     '14 bottles of beer on the wall', '15 bottles of beer on the wall', 
     '16 bottles of beer on the wall', '17 bottles of beer on the wall', 
     '18 bottles of beer on the wall', '19 bottles of beer on the wall'], dtype=object) 
+1

啊哈,謝謝!文檔是空的。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.field.html –

+0

不客氣!它也將採用字段的名稱,順便說一句。 – JaminSore