0

I have csv file with some data. I am trying to read numpy arrays from csv file, so here is code of the program:

import numpy as np
train = csv.reader(open(sys.argv[1], 'r'))
X = []
y = []
for row in train:
    X.append(row[1:])
    y.append(row[0])
X = np.array(X)
y = np.array(y)

I know that Python syntax is very unusual. So is there any way to write turn loop in something like that?

import numpy as np
train = csv.reader(open(sys.argv[1], 'r'))
X, y = [... for row in train]

1 Answer 1

2

Why you are not reading the whole csv file using np.loadtxt?

>>> from io import StringIO
>>> txt = '''
... 1, 2, 3
... 4, 5, 6
... 7, 8, 9'''
>>> 
>>> xs = np.loadtxt(StringIO(txt), delimiter=',')
>>> xs
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])
>>> 
>>> x, y = xs[:, 1:], xs[:, 0]
>>> x
array([[ 2.,  3.],
       [ 5.,  6.],
       [ 8.,  9.]])
>>> y
array([ 1.,  4.,  7.])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.