The Wayback Machine - https://web.archive.org/web/20240530021157/https://www.geeksforgeeks.org/python-read-csv-using-pandas-read_csv/
Open In App

Pandas Read CSV in Python

Last Updated : 24 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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, engine=None, skiprows=None, nrows=None) 

Parameters: 

  • filepath_or_buffer: Location of the csv file. It accepts any string path or URL of the file.
  • sep: It stands for separator, default is ‘, ‘.
  • header: It accepts int, a list of int, row numbers to use as the column names, and the start of the data. If no names are passed, i.e., header=None, then, it will display the first column as 0, the second as 1, and so on.
  • usecols: Retrieves only selected columns from the CSV file.
  • nrows: Number of rows to be displayed from the dataset.
  • index_col: If None, there are no index numbers displayed along with records.  
  • skiprows: Skips passed rows in the new data frame.

Read CSV File using Pandas read_csv

Before using this function, we must import the Pandas library, we will load the CSV file using Pandas.

PYTHON3




# Import pandas
import pandas as pd
 
# reading csv file
df = pd.read_csv("people.csv")
print(df.head())


Output:

  First Name Last Name     Sex                       Email Date of birth  Job Title        
0 Shelby Terrell Male elijah57@example.net 1945-10-26 Games developer
1 Phillip Summers Female bethany14@example.com 1910-03-24 Phytotherapist
2 Kristine Travis Male bthompson@example.com 1992-07-02 Homeopath
3 Yesenia Martinez Male kaitlinkaiser@example.com 2017-08-03 Market researcher
4 Lori Todd Male buchananmanuel@example.net 1938-12-01 Veterinary surgeon

Using sep in read_csv()

In this example, we will take a CSV file and then add some special characters to see how the sep parameter works.

Python3




# sample = "totalbill_tip, sex:smoker, day_time, size
# 16.99, 1.01:Female|No, Sun, Dinner, 2
# 10.34, 1.66, Male, No|Sun:Dinner, 3
# 21.01:3.5_Male, No:Sun, Dinner, 3
#23.68, 3.31, Male|No, Sun_Dinner, 2
# 24.59:3.61, Female_No, Sun, Dinner, 4
# 25.29, 4.71|Male, No:Sun, Dinner, 4"
 
# Importing pandas library
import pandas as pd
 
# Load the data of csv
df = pd.read_csv('sample.csv',
                 sep='[:, |_]',
                 engine='python')
 
# Print the Dataframe
print(df)


Output:

        totalbill   tip Unnamed: 2   sex smoker Unnamed: 5     day    time  Unnamed: 8  size 
16.99 NaN 1.01 Female No NaN Sun NaN Dinner NaN 2
10.34 NaN 1.66 NaN Male NaN No Sun Dinner NaN 3
21.01 3.50 Male NaN No Sun NaN Dinner NaN 3.0 None
23.68 NaN 3.31 NaN Male No NaN Sun Dinner NaN 2
24.59 3.61 NaN Female No NaN Sun NaN Dinner NaN 2
25.29 NaN 4.71 Male NaN No Sun NaN Dinner NaN 4

Using usecols in read_csv()

Here, we are specifying only 3 columns,i.e.[“First Name”, “Sex”, “Email”] to load and we use the header 0 as its default header.

Python3




df = pd.read_csv('people.csv',
        header=0,
        usecols=["First Name", "Sex", "Email"])
# printing dataframe
print(df.head())


Output:

  First Name     Sex                       Email
0 Shelby Male elijah57@example.net
1 Phillip Female bethany14@example.com
2 Kristine Male bthompson@example.com
3 Yesenia Male kaitlinkaiser@example.com
4 Lori Male buchananmanuel@example.net

Using index_col in read_csv()

Here, we use the “Sex” index first and then the “Job Title” index, we can simply reindex the header with index_col parameter.

Python3




df = pd.read_csv('people.csv',
        header=0,
        index_col=["Sex", "Job Title"],
        usecols=["Sex", "Job Title", "Email"])
 
print(df.head())


Output:

                                                Email
Sex Job Title
Male Games developer elijah57@example.net
Female Phytotherapist bethany14@example.com
Male Homeopath bthompson@example.com
Market researcher kaitlinkaiser@example.com
Veterinary surgeon buchananmanuel@example.net

Using nrows in read_csv()

Here, we just display only 5 rows using nrows parameter.

Python3




df = pd.read_csv('people.csv',
        header=0,
        index_col=["Sex", "Job Title"],
        usecols=["Sex", "Job Title", "Email"],
                nrows=3)
 
print(df)


Output:

                                        Email
Sex Job Title
Male Games developer elijah57@example.net
Female Phytotherapist bethany14@example.com
Male Homeopath bthompson@example.com

Using skiprows in read_csv()

The skiprows help to skip some rows in CSV, i.e, here you will observe that the rows mentioned in skiprows have been skipped from the original dataset.

Python3




df= pd.read_csv("people.csv")
print("Previous Dataset: ")
print(df)
# using skiprows
df = pd.read_csv("people.csv", skiprows = [1,5])
print("Dataset After skipping rows: ")
print(df)


Output:

Previous Dataset:
First Name Last Name Sex Email Date of birth Job Title
0 Shelby Terrell Male elijah57@example.net 1945-10-26 Games developer
1 Phillip Summers Female bethany14@example.com 1910-03-24 Phytotherapist
2 Kristine Travis Male bthompson@example.com 1992-07-02 Homeopath
3 Yesenia Martinez Male kaitlinkaiser@example.com 2017-08-03 Market researcher
4 Lori Todd Male buchananmanuel@example.net 1938-12-01 Veterinary surgeon
5 Erin Day Male tconner@example.org 2015-10-28 Management officer
6 Katherine Buck Female conniecowan@example.com 1989-01-22 Analyst
7 Ricardo Hinton Male wyattbishop@example.com 1924-03-26 Hydrogeologist
Dataset After skipping rows:
First Name Last Name Sex Email Date of birth Job Title
0 Shelby Terrell Male elijah57@example.net 1945-10-26 Games developer
1 Kristine Travis Male bthompson@example.com 1992-07-02 Homeopath
2 Yesenia Martinez Male kaitlinkaiser@example.com 2017-08-03 Market researcher
3 Lori Todd Male buchananmanuel@example.net 1938-12-01 Veterinary surgeon
4 Katherine Buck Female conniecowan@example.com 1989-01-22 Analyst
5 Ricardo Hinton Male wyattbishop@example.com 1924-03-26 Hydrogeologist



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
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
Using csv module to read the data in Pandas
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There were various formats of CSV until its standardization. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can ma
3 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
How to read csv file with Pandas without header?
Prerequisites: Pandas A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file. Syntax: read_csv("file name", header=None) ApproachImport
1 min read
How to read all CSV files in a folder in Pandas?
In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content. Approach:Import necessary python packages like pandas, glob,
1 min read
Copying Csv Data Into Csv Files Using Python
CSV files, the stalwarts of information exchange, can be effortlessly harnessed to extract specific data or merge insights from multiple files. In this article, we unveil five robust approaches, transforming you into a virtuoso of CSV data migration in Python. Empower your data-wrangling endeavors, mastering the art of copying and organizing inform
4 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
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
Python - Read CSV Columns Into List
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 libr
3 min read
Practice Tags :