通过命令行读取CSV作为Numpy 2d Matrix时出错

时间:2017-08-24 05:05:20

标签: python csv numpy genfromtxt

我正在尝试使用 csv.reader()函数将CSV文件中的数据读取为numpy矩阵,以使用以下代码将其存储到Numpy 2d矩阵中:

import sys
import csv
filename1 = sys.argv[0]
reader = csv.reader(open(filename1, "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype('int')

但是当我运行此代码时,我收到以下错误:

Traceback (most recent call last):   File "q1.py", line 94, in <module>
result = numpy.array(x).astype('int') ValueError: setting an array element with a sequence.

我也跟着这个this,但后来我得到了不同的错误信息:

 Traceback (most recent call last):
  File "q1-prac.py", line 24, in <module>
    result = genfromtxt(filename1, delimiter=',')
  File "/home/ashutosh/.local/lib/python2.7/site-packages/numpy/lib/npyio.py", line 1769, in genfromtxt
    raise ValueError(errmsg)
ValueError: Some errors were detected !
    Line #13 (got 3 columns instead of 1)
    Line #22 (got 3 columns instead of 1)
    Line #36 (got 2 columns instead of 1)
    Line #37 (got 2 columns instead of 1)
    Line #40 (got 4 columns instead of 1)
    Line #46 (got 2 columns instead of 1)

请为此建议一些解决方案。

1 个答案:

答案 0 :(得分:0)

我认为错误是因为您初始化了一维numpy数组并尝试将3列添加到一行中。尝试初始化3d数组并执行相同的操作