Open In App

Python – Read CSV Columns Into List

Last Updated : 17 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. In this article, we will read data from a CSV file into a list. We will use the panda’s library to read the data into a list. 

File Used: file.

Method 1: Using Pandas

Here, we have the read_csv() function which helps to read the CSV file by simply creating its object. The column name can be written inside this object to access a particular column, the same as we do in accessing the elements of the array. Pandas library has a function named as tolist() that converts the data into a list that can be used as per our requirement. So, we will use this to convert the column data into a list. Finally, we will print the list.

Approach:

  • Import the module.
  • Read data from CSV file.
  • Convert it into the list.
  • Print the list.

Below is the implementation:

Python3




# importing module
from pandas import *
 
# reading CSV file
data = read_csv("company_sales_data.csv")
 
# converting column data to list
month = data['month_number'].tolist()
fc = data['facecream'].tolist()
fw = data['facewash'].tolist()
tp = data['toothpaste'].tolist()
sh = data['shampoo'].tolist()
 
# printing list data
print('Facecream:', fc)
print('Facewash:', fw)
print('Toothpaste:', tp)
print('Shampoo:', sh)


Output:

Method 2: Using csv module

In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys. We will create empty lists so that we can store the values in it. Finally, we access the key values and append them into the empty lists and print that list.

Python3




# importing the module
import csv
 
# open the file in read mode
filename = open('company_sales_data.csv', 'r')
 
# creating dictreader object
file = csv.DictReader(filename)
 
# creating empty lists
month = []
totalprofit = []
totalunit = []
 
# iterating over each row and append
# values to empty list
for col in file:
    month.append(col['month_number'])
    totalprofit.append(col['moisturizer'])
    totalunit.append(col['total_units'])
 
# printing lists
print('Month:', month)
print('Moisturizer:', totalprofit)
print('Total Units:', totalunit)


Output:



Previous Article
Next Article

Similar Reads

Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Python - Read CSV Column into List without header
Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let's see
2 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV con
2 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Pandas Read CSV in Python
CSV files are the Comma Separated Files. To access data from the CSV file, we require a function read_csv() from Pandas that retrieves data in the form of the data frame. Syntax of read_csv() Here is the Pandas read CSV syntax with its parameters. Syntax: pd.read_csv(filepath_or_buffer, sep=' ,' , header='infer', index_col=None, usecols=None, engin
4 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file
4 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
How to convert CSV columns to text in Python?
In this article, we are going to see how to convert CSV columns to text in Python, and we will also see how to convert all CSV column to text. Approach: Read .CSV file using pandas dataframe.Convert particular column to list using list() constructorThen sequentially convert each element of the list to a string and join them using a specific charact
2 min read
Practice Tags :