使用numpy genfromtxt和loadtxt读取csv文件

时间:2018-10-05 12:02:49

标签: python python-3.x csv numpy

以下是尝试读取的数据示例:

107,4205,934,-1869,97,3917,0,-5154,23,-447
69,-1014,-1449,-4347,177,-1977,4463,2824,1,80
177,-1581,5028,4519,161,-372,5900,1677,2,36
175,-800,-5028,-2571,195,-1794,-6410,-3589,1,-25
107,-1962,-3457,-2336,109,-2018,-7614,-1376,1,9
72,-138,-6388,1388,76,1447,789,6315,1,38
78,1538,6666,4871,67,5074,6119,7611,3,-50
65,-4615,307,-9384,85,-6235,-5176,-7999,3,-12

但是我不断收到这些错误

>>> dataset = numpy.loadtxt(r"C:\data.csv",delimiter=',',dtype=str)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
dataset = numpy.loadtxt(r"C:\data.csv",delimiter=',',dtype=str)
File "C:\Program Files\Python36\lib\site-packages\numpy\lib\npyio.py", line 
1101, in loadtxt
for x in read_data(_loadtxt_chunksize):
 File "C:\Program Files\Python36\lib\site-packages\numpy\lib\npyio.py", line 
1025, in read_data
% line_num)
ValueError: Wrong number of columns at line 2

>>> dataset = numpy.genfromtxt(r"C:\data.csv",delimiter=',')
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dataset = numpy.genfromtxt(r"C:\data.csv",delimiter=',')
File "C:\Program Files\Python36\lib\site-packages\numpy\lib\npyio.py", line 
2031, in genfromtxt
raise ValueError(errmsg)
ValueError: Some errors were detected !
Line #2 (got 1 columns instead of 10)
Line #4 (got 1 columns instead of 10)
Line #6 (got 1 columns instead of 10)

我尝试更改loadtxt和genfromtxt函数的输入,但是nothin似乎起作用。同样,关于第2行的列数错误的错误也令人好奇。该数据很简单,没有标题。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我的csv文件是用Unicode而不是ANSI编写的。

在更改为ANSI时,它没有任何问题!