0

I am trying to read data in CSV file as numpy matrix using csv.reader() function to store it into Numpy 2d matrix using the following code:

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

But when I run this code, I get the following error:

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.

I also followed this this but then I get different error message:

 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)

Please suggest some solution to this.

  • You need to skip the starting line (if you have the header). While reading matrix the array should be of same length. Show 2 to 3 lines of CSV, I can help you better. – Bhuvan Kumar Aug 24 '17 at 05:14
  • What does the list `x` look like? Also verify the `filename1`. Usually `sys.argv[0]` is the name of the script, while `argv[1]` is the first argument string. You may also need to show a us a sample of the `csv` file. – hpaulj Aug 24 '17 at 06:14
  • Thanks @hpaulj that was my mistake. sys.argv[0] was the name of file being executed, so there was the problem. – Ashutosh Mishra Aug 24 '17 at 11:43

1 Answers1

0

I think the error is because you have initialized the one-dimensional numpy array and trying to add 3 columns into a single row. try initializing 3d array and do the same

Max
  • 1,283
  • 9
  • 20