Open In App

How to Read CSV Files with NumPy?

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Reading CSV files is a common task when working with data in Python. In this article we will see how to read CSV files using Numpy’s loadtxt() and genfromtxt() methods.

1. Using NumPy loadtxt() method

The loadtext() method is faster and simpler for reading CSV files. It is best when the file has consistent columns and no missing values.

Syntax: numpy.loadtxt(‘filename.csv’, delimiter=’,’, dtype=str)

Parameters:

  • filename: File name or path link to the CSV file.
  • delimiter (optional): Delimiter to consider while creating array of values from text default is whitespace.
  • encoding (optional): Encoding used to decode the input file.
  • dtype (optional): Data type of the resulting array

Return: Returns a NumPy array.

We will be using Numpy library for its implementation. You can download the sample dataset from here.

Python
import numpy as np
arr = np.loadtxt("/content/CAR.csv",
				delimiter=",", dtype=str)
display(arr)

Output:

csv

Using numpy’s loadtxt()

2. Using NumPy genfromtxt() method

The genfromtxt() function is used to handle datasets with missing values or varied data types. It’s perfect for more complex CSV files that require handling.

Syntax: numpy.genfromtxt(‘filename.csv’, delimiter=’,’, dtype=None, skip_header=0, missing_values=None, filling_values=None, usecols=None)

Parameters:

  • filename: File name or path to the CSV file.
  • delimiter (optional): Used consider while creating array of values from text default is any consecutive white spaces act as a delimiter.
  • missing_values (optional): Set of strings to use incase of a missing value.
  • dtype (optional): Data type of the resulting array.

Return: Returns NumPy array.

Python
import numpy as np
arr = np.genfromtxt("/content/CAR.csv",
                    delimiter=",", dtype=str)
display(arr)

Output:

csv2

Using numpy’s genfromtxt()

By using NumPy’s loadtxt() and genfromtxt() methods we can efficiently read and process CSV files whether they are simple or contain complex data structures this makes NumPy a good choice for data analysis tasks.



Next Article
Article Tags :
Practice Tags :

Similar Reads