Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read CSV data into a record array in NumPy?

I wonder if there is a direct way to import the contents of a CSV file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame?

Or is the best way to use csv.reader() and then apply something like numpy.core.records.fromrecords()?

like image 240
hatmatrix Avatar asked Aug 19 '10 04:08

hatmatrix


People also ask

How do you read a CSV file into an array in Python?

Use numpy. loadtxt() to Read a CSV File Into an Array in Python. As the name suggests, the open() function is used to open the CSV file. NumPy's loadtxt() function helps in loading the data from a text file.

How can a CSV data file be loaded 1 with Python Standard Library 2 with NumPy?

Method 1: Using loadtxt method To import data from a text file, we will use the NumPy loadtxt() method. To use this function we need to make sure that the count of entries in each line of the text document should be equal.

How do I convert a CSV file to a matrix in Python?

Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to NumPy np. genfromtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.


1 Answers

You can use Numpy's genfromtxt() method to do so, by setting the delimiter kwarg to a comma.

from numpy import genfromtxt my_data = genfromtxt('my_file.csv', delimiter=',') 

More information on the function can be found at its respective documentation.

like image 159
Andrew Avatar answered Oct 07 '22 16:10

Andrew