2012-10-13 23 views
4

時,要保持字符串我有一個數據結構,看起來像這樣:轉換Python列表爲numpy的結構數組

data = [ ('a', 1.0, 2.0), 
     ('b', 2.0, 4.0), 
     ('c', 3.0, 6.0) ] 

我想將其轉換成使用numpy的結構化陣列。但是,當我嘗試以下方法,我把花車,但我失去了字符串信息:

import numpy 
x = numpy.array(data, dtype=[('label', str), ('x', float), ('y', float)]) 
print x 

結果造成:

>>> [('', 1.0, 2.0) ('', 2.0, 4.0) ('', 3.0, 6.0)] 

誰能解釋爲什麼出現這種情況,我怎麼可能保持串信息?

+0

X = numpy.array(數據,D型= [('label',(str,1)),('x',float),('y',float)]) – luke14free

回答

4

你可以看到這個問題,如果你要打印出數組並仔細看看:

>>> numpy.array(data, dtype=[('label', str), ('x', float), ('y', float)]) 
array([('', 1.0, 2.0), ('', 2.0, 4.0), ('', 3.0, 6.0)], 
     dtype=[('label', '|S0'), ('x', '<f8'), ('y', '<f8')]) 

第一場有'|S0'數據類型 - 一個零寬度串場。使字符串場長 - 這裏有一個2字符字符串字段:

>>> numpy.array(data, dtype=[('label', 'S2'), ('x', float), ('y', float)]) 
array([('a', 1.0, 2.0), ('b', 2.0, 4.0), ('c', 3.0, 6.0)], 
     dtype=[('label', '|S2'), ('x', '<f8'), ('y', '<f8')]) 

你也可以這樣來做,如記錄here

>>> numpy.array(data, dtype=[('label', (str, 2)), ('x', float), ('y', float)]) 
array([('a', 1.0, 2.0), ('b', 2.0, 4.0), ('c', 3.0, 6.0)], 
     dtype=[('label', '|S2'), ('x', '<f8'), ('y', '<f8')]) 
相關問題