How do I read CSV data into a record array in NumPy?
You can use the numpy.genfromtxt()
function to read CSV data into a NumPy record array. Here is an example code snippet:
import numpy as np
data = np.genfromtxt('data.csv', delimiter=',', names=True, dtype=None)
In this example, data.csv
is the name of the CSV file you want to read, delimiter=','
specifies that the columns in the file are separated by commas, names=True
tells the function to use the first row of the file as the field names for the record array, and dtype=None
tells the function to automatically determine the data types for each field.
You can also specify the dtype using a list of tuples, where each tuple contains the name and data type of a field, like this:
dtype=[('field1', 'i4'), ('field2', 'f4'), ('field3', 'a10')]
data = np.genfromtxt('data.csv', delimiter=',', names=True, dtype=dtype)
Here, 'i4' is the code for a 4-byte integer, 'f4' is the code for a 4-byte floating-point number, and 'a10' is the code for a 10-byte string.