Skip to main content
 首页 » 编程设计

python之numpy.loadtxt 和制表符分隔值 : data type not understood

2025年05月04日7sharpest

我在使用 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)) 

这将返回无法理解的数据类型。我在这里缺少什么?

请您参考如下方法:

为了实现快速索引,NumPy 依赖于每个具有固定宽度的数据类型。所以如果你指定一个字符串数据类型,你还必须指定字符串中的字节数。所以

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')])