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()
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With