我在使用numpy.loadtxt
导入制表符分隔值时遇到问题。
我需要导入的行具有以下形式:
01-Aug-2013 1143_051-100 r 702 135 32 7
我只想阅读第0,2,3,4,5,6列。这就是我到目前为止所做的:
numpy.loadtxt(test,dtype= (str,str,int,int,int,int), delimiter= "\t", usecols = (0,2,3,4,5,6))
返回data type not understood
。我在这里缺少什么?
答案 0 :(得分:1)
为了实现快速索引,NumPy依赖于具有固定宽度的每个dtype。因此,如果指定字符串dtype,则还必须指定字符串中的字节数。所以
dtype = '|S11,|S1,<i4,<i4,<i4,<i4'
适用于您发布的数据。
但是,当字符串具有可变宽度时,使用np.genfromtxt
代替np.loadtxt
会更容易,因为您可以指定dtype=None
并让np.genfromtxt
做出有根据的猜测每列的dtype。
In [15]: np.genfromtxt('data', delimiter='\t', dtype=None, usecols=(0,2,3,4,5,6))
Out[15]:
array(('01-Aug-2013', 'r', 702, 135, 32, 7),
dtype=[('f0', 'S11'), ('f1', 'S1'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<i4'), ('f5', '<i4')])
或
In [16]: np.loadtxt('data', delimiter='\t', dtype='|S11,|S1,<i4,<i4,<i4,<i4', usecols=(0,2,3,4,5,6))
Out[16]:
array(('01-Aug-2013', 'r', 702, 135, 32, 7),
dtype=[('f0', 'S11'), ('f1', 'S1'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<i4'), ('f5', '<i4')])