2011-10-12 62 views
8

這給了我一個錯誤:如何創建一個numpy記錄數組?

import numpy as np 
x = np.array([[1, 'O', 1]], 
      dtype=np.dtype([('step', 'int32'), 
          ('symbol', '|S1'), 
          ('index', 'int32')])) 

TypeError: expected a readable buffer object 

我不知道爲什麼這會失敗?

Alternatlively,我怎麼能強迫這樣的語句來工作?

x = np.array([[1, 'O', 1]]) 

然後

x.dtype = np.dtype([('step', 'int32'),('symbol', '|S1'),('index', 'int32')]) 

x.view(dtype=np.dtype([('step', 'int32'),('symbol', '|S1'),('index', 'int32')])) 

兩個給我

ValueError: new type not compatible with array. 

編輯

如果我嘗試進入每個記錄作爲一個元組,它會認爲三是單個值,而不是三個不同的領域?例如:

import numpy as np 
x = np.array([(1, 'O', 1)], 
      dtype=np.dtype([('step', 'int32'), 
          ('symbol', '|S1'), 
          ('index', 'int32')])) 

似乎很好,直到我這樣做:

import numpy.lib.recfunctions as rec 
rec.append_fields(x,'x',x['index']+1) 

給我

TypeError: object of type 'numpy.int32' has no len() 

大概是因爲x.shape是(1),而不是(1,3)。

回答

7

使各行的元組,而不是一個列表:

import numpy as np 
x = np.array([(1, 'O', 1)], 
      dtype=np.dtype([('step', 'int32'), 
          ('symbol', '|S1'), 
          ('index', 'int32')])) 

numpy的開發商Robert Kern explains

As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.

+0

謝謝,但那麼x的形狀爲(1)而不是(1,3)? – hatmatrix

+0

這就是定義結構化數組時應該得到的結果。您可以使用如下語法訪問列:'x ['symbol']' – unutbu

+0

謝謝我將附加字段作爲單獨問題發佈。 – hatmatrix

1

我將展示創建記錄陣列的一個更一般的方式:

# prepare the array with different types 
recarr = np.zeros((4,), dtype=('i4,f4,a10')) 

# creating the columns 
col1 = [1, 7, 2, 3] 
col2 = [1.1, 0.5, 2, 7.45] 
col3 = ['This', 'is', 'text', '!!!'] 

# create a list of tuples from columns 
prepare = zip(col1, col2, col3) 

# assigning value so recarr 
recarr[:] = prepare 

現在您可以爲每個列分配名稱:

recarr.dtype.names = ('ID' , 'price', 'text') 

和以後得到的數值此列:

print recarr('price') 
相關問題