How to load CSV file using NumPy in Python

This tutorial will help you to get an idea about how to load a CSV file using NumPy in Python. With the Python NumPy library, large amounts of data can be loaded faster by reading CSV files. In order to read huge amounts of data from CSV files, NumPy is recommended. So read the tutorial very carefully to clear your concepts regarding the topic.

1. Using built-in Python open() function

The most common and simple method to read the CSV file is the built-in Python open() function. In this method load the path of the CSV file in the open() function of Python and then by using for loop in the file print the data. Look at the syntax given below to clear your doubts.

data_file = open("sample.csv")
for i in data_file:


load CSV file using NumPy in Python

2. Using NumPy loadtxt() method

Another method to load the CSV file is by using the NumPy loadtxt() method in Python. In this method firstly import the NumPy module. Using this function, we must make sure that each line of the text document has the same number of entries and at last display the array. For reference the following code is given below:

#import the numpy module
import numpy as np
# using loadtxt() method load the CSV file
arr = np.loadtxt("sample.csv",
                 delimiter=",", dtype=str)
#display the array


NumPy loadtxt()

3. Using built-in Python CSV module

In Python, there is a built-in csv.reader() function that reads each line of the data or CSV file you pass it. As a result of this function, every line in the CSV file will be read and converted into a list of items based on the data in each line. In this method begin with importing the NumPy and CSV module and with open function load the CSV file and at last print the array. Look at the code given below:

#import the numpy module
import numpy as np
# import the csv module
import csv
#use open() function to load the file
with open("sample.csv", 'r') as t:
    data_file = list(csv.reader(t, delimiter=","))
data_file = np.array(data_file)


built-in Python CSV module

Leave a Reply

Your email address will not be published. Required fields are marked *