2012-10-13 25 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')]) 
相关问题