Skip to main content
 首页 » 编程设计

python之使用 genfromtxt 和第一列字符串读取 csv 的 Numpy IndexError

2024年10月25日31myhome

我有一些代码可以读取制表符分隔值 (tsv) 的文件,当第一列是数字时工作正常,但当它是字符串时失败。

import os 
import numpy as np 
 
input_file = os.path.normpath('C:/Users/sturaroa/Documents/PycharmProjects/my_file.tsv') 
 
# read values from file, by column 
my_data = np.genfromtxt(input_file, delimiter='\t', skip_header=0) 
print('my_data\n' + str(my_data)) 
 
groups = my_data[:, 0]  # 1st column 
X = my_data[:, 1]  # 2nd column 
Y = my_data[:, 2]  # 3rd column 
errors = my_data[:, 3]  # 4th column (errors) 
print('\ngroups ' + str(groups) + '\nX ' + str(X) + '\nY ' + str(Y) + '\nerrors ' + str(errors)) 

这是文件内容(制表符分隔)

2.4    2    4.0    0.0 
2.4    4    8.210526    0.7254761 
2.9    4    8.4    0.8081221 
2.9    6    12.52    1.0544369 

程序打印这个

my_data 
[[  2.4         2.          4.          0.       ] 
 [  2.4         4.          8.210526    0.7254761] 
 [  2.9         4.          8.4         0.8081221] 
 [  2.9         6.         12.52        1.0544369]] 
 
groups [ 2.4  2.4  2.9  2.9] 
X [ 2.  4.  4.  6.] 
Y [  4.         8.210526   8.4       12.52    ] 
errors [ 0.         0.7254761  0.8081221  1.0544369] 

我看过 this question建议使用 dtype=None。但是,如果我这样做,我会收到此错误

Traceback (most recent call last): 
  File "C:/Users/sturaroa/Documents/PycharmProjects/2d_plot_test.py", line 11, in <module> 
    groups = my_data[:, 0]  # 1st column 
IndexError: too many indices for array 

我需要调整我的代码以处理这样的输入

something    2    4.0    0.0 
something    4    8.210526    0.7254761 
some_other_thing    8.4    0.8081221 
some_other_thing    12.52    1.0544369 

第一列是可变长度的字符串,其他列是数字(整数或 float )。

我在 Python 2.7 上使用 numpy 1.9.2。

请您参考如下方法:

当您使用 dtype=None 读取并且有字符串列时,genfromtxt 会为您提供一个结构化数组。打印 my_data,并查看其形状和数据类型(并将其添加到您的问题中)。

您可以按名称而不是索引访问此类数组的列。由于您不使用标题或提供名称,因此将使用 my_data['f0'] 访问第一列。

您可能需要查看有关结构化数组的 numpy 文档。