Read CSV to Array in Python

Lakshay Kapoor Jan 30, 2023 May 28, 2021
  1. Use numpy.loadtxt() to Read a CSV File Into an Array in Python
  2. Use the list() Method to Read a CSV File Into a 1D Array in Python
Read CSV to Array in Python

The use of CSV files is widespread in the field of data analysis/data science in Python. CSV stands for Comma Separated Values. These types of files are used to store data in the form of tables and records. In these tables, there are a lot of columns separated by commas. One of the tasks in manipulating these CSV files is importing these files in the form of data arrays.

This tutorial will introduce different methods to import CSV files in the form of data arrays.

Use numpy.loadtxt() to Read a CSV File Into an Array in Python

As the name suggests, the open() function is used to open the CSV file. NumPy’s loadtxt() function helps in loading the data from a text file. In this function’s arguments, there are two parameters that must be mentioned: file name or the variable in which the file name is stored, and the other one is called delimiter, which denotes the string used for separating the values. The default value of the delimiter is whitespace.

Example:

import numpy as np

with open("randomfile.csv") as file_name:
    array = np.loadtxt(file_name, delimiter=",")

print(array)

Here, note that the delimiter value has been set to a comma. Therefore, the separator in the returned array is a comma.

Use the list() Method to Read a CSV File Into a 1D Array in Python

Here we use the csv module of Python, which is used to read that CSV file in the same tabular format. More precisely, the reader() method of this module is used to read the CSV file.

Finally, the list() method takes all the sequences and the values in tabular format and converts them into a list.

Example:

import csv

with open("randomfile.csv") as file_name:
    file_read = csv.reader(file_name)

array = list(file_read)
 
print(array)

Here, we store the data read by the reader() function in a variable and use that variable to convert that data into a list.

Lakshay Kapoor avatar Lakshay Kapoor avatar

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

LinkedIn

Related Article - Python CSV

Related Article - Python Array