Numpy没有正确接受字符串?

时间:2017-04-24 20:44:23

标签: python numpy

我有一些CSV格式的数据(为简单起见,我删除了一些列):

Year,Region,Round,Diff
2014,South,Second Round,-24
2015,West,First Round,48
# ...lots of rows of this

我想同时使用RegionRound列中的字符串数据以及Diff列中的整数数据。

以下是我的相关代码:

import sklearn
import numpy as np
from numpy import genfromtxt
from StringIO import StringIO

# Some other code...

my_dtype=[('Year', int), ('Region', str),('Round', str),('Diff', int)] 
data = np.genfromtxt(my_file, delimiter=',',names=True,dtype=my_dtype)
print data

当我打印数据时,我得到以下内容。 NumPy使每个字符串都为空字符串。

[ ( 2014, '', '', -24)
( 2010, '', '', 48)
...]

有谁知道如何解决这个问题?我使用dtype属性错了吗?或者是其他东西?提前谢谢。

1 个答案:

答案 0 :(得分:1)

不要将str放在文本字段的数据类型中,而是使用最大字符串长度的S格式:

In [10]: my_dtype = [('Year', int), ('Region', 'S8'), ('Round', 'S16'), ('Diff', int)] 

In [11]: data = np.genfromtxt('regions.csv', delimiter=',', names=True, dtype=my_dtype)

In [12]: data
Out[12]: 
array([(2014, b'South', b'Second Round', -24),
       (2015, b'West', b'First Round',  48)], 
      dtype=[('Year', '<i8'), ('Region', 'S8'), ('Round', 'S16'), ('Diff', '<i8')])

您也可以使用dtype=None并让genfromtxt()为您确定数据类型:

In [13]: data = np.genfromtxt('regions.csv', delimiter=',', names=True, dtype=None)

In [14]: data
Out[14]: 
array([(2014, b'South', b'Second Round', -24),
       (2015, b'West', b'First Round',  48)], 
      dtype=[('Year', '<i8'), ('Region', 'S5'), ('Round', 'S12'), ('Diff', '<i8')])