2011-10-12 16 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 

これが失敗した理由を私は知らないのですか?

代わりに、このステートメントのようなものを強制するにはどうすればよいですか?

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. 

を与える編集

タプルとして各レコードを入力しようとすると、トリプルが3つの別々のフィールドではなく単一の値であると考えられますか?例えば:私はこれを行うまで

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

は罰金だ:x.shapeは、(1)ではなく(1,3)であるため、

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

は私に、おそらく

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

を与えます。

答えて

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') 
関連する問題