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

565    Asked by ColinPayne in Python , Asked on Apr 15, 2021

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()?

Answered by Colin Payne

To solve numpy import csv you can use NumPy modules genfromtxt() function, In this function’s argument, you need to set the delimiter to a comma.

from numpy import genfromtxt

  my_data = genfromtxt('my_file.csv', delimiter=',')

You can also use the pandas read_csv function to read CSV data into a record array in NumPy.

import pandas as pd

df=pd.read_csv('myfile.csv', sep=',',header=None)
df.values array([[ 1. , 2. , 3. ], [ 4. , 5.5, 6. ]])


Your Answer

Interviews

Parent Categories