How to import csv file as numpy.array in python? [duplicate] How to import csv file as numpy.array in python? [duplicate] numpy numpy

How to import csv file as numpy.array in python? [duplicate]


numpy.genfromtxt() is the best thing to use here

import numpy as npcsv = np.genfromtxt ('file.csv', delimiter=",")second = csv[:,1]third = csv[:,2]>>> secondOut[1]: array([ 432.,  300.,  432.])>>> thirdOut[2]: array([ 1.,  1.,  0.])


You can use numpy.loadtxt:

In [15]: !cat data.csvdfaefew,432,1vzcxvvz,300,1ewrwefd,432,0In [16]: second, third = loadtxt('data.csv', delimiter=',', usecols=(1,2), unpack=True, dtype=int)In [17]: secondOut[17]: array([432, 300, 432])In [18]: thirdOut[18]: array([1, 1, 0])

Or numpy.genfromtxt

In [19]: second, third = genfromtxt('data.csv', delimiter=',', usecols=(1,2), unpack=True, dtype=None)

The only change in the arguments is that I used dtype=None, which tells genfromtxt to infer the data type from the values that it finds in the file.