read csv using numpy in python

To read a CSV file using NumPy in Python, we can use the genfromtxt() function of NumPy. Here's an example code:

main.py
import numpy as np

# Load the CSV file into a 2D NumPy array
data = np.genfromtxt('data.csv', delimiter=',')

# Check the shape of the 2D NumPy array
print(data.shape)

# Print the contents of the 2D NumPy array
print(data)
225 chars
11 lines

In this code, we first import the NumPy library. Then, we use the genfromtxt() function to read the CSV file called data.csv and store its contents in a 2D NumPy array called data. The delimiter=',' argument specifies that the CSV file is comma-separated.

We also print out the shape of the 2D NumPy array and its contents.

Note: If there are missing values in the CSV file, you can use the filling_values parameter to replace them with a specified value.

related categories

gistlibby LogSnag