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

Pandas Read CSV in Python

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Pandas 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.

PYTHON
# 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.

Python
# 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.

Python
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.

Python
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.

Python
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.

Python
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

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
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 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
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
How to Read CSV Files with NumPy?
In this article, we will discuss how to read CSV files with Numpy in Python. Reading CSV files using Python NumPy library helps in loading large amount of data quicker. Due to performance reason, NumPy is preferred while reading huge amount of data from CSV files. Dataset in use: Read CSV Files using built-in Python open() function Here we are not
3 min read
How to read CSV data into a record array in NumPy?
In NumPy, a record array (or recarray) is a specialized array that allows you to access fields as attributes, providing a convenient way to handle structured data. It is essentially a structured array that is wrapped in an object-oriented interface, making it easier to work with data that has named columns, similar to a DataFrame in pandas. Key Fea
3 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
Convert CSV to HTML Table using Python Pandas and Flask Framework
In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework. Sample CSV file : USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME booker12,9012,Rachel,Booker grey07,2070,Laura,Grey johnson81,4081,Craig,Johnson jenkins46,9346,Mary,Jenkins smith79,5079,Jamie,SmithStepwise ImplementationCreating Environment Ste
2 min read
How to skip rows while reading csv file using 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 skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
How to export Pandas DataFrame to a CSV file?
Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. DataFrame.to_csv() Syntax : to_csv(parameters) Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of length 1. Field delimiter for the output file. na_
3 min read
Pandas - DataFrame to CSV file using tab separator
Let's see how to convert a DataFrame to a CSV file using the tab separator. We will be using the to_csv() method to save a DataFrame as a csv file. To save the DataFrame with tab separators, we have to pass "\t" as the sep parameter in the to_csv() method. Approach : Import the Pandas and Numpy modules.Create a DataFrame using the DataFrame() metho
1 min read
Export Pandas dataframe to a CSV file
Suppose you are working on a Data Science project and you tackle one of the most important tasks, i.e, Data Cleaning. After data cleaning, you don't want to lose your cleaned data frame, so you want to save your cleaned data frame as a CSV. Let us see how to export a Pandas DataFrame to a CSV file. Pandas enable us to do so with its inbuilt to_csv(
2 min read
Concatenating CSV files using Pandas module
Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module. Suppose we have one .csv file named Employee.csv which contains some records and it is as below: There is another .csv file named Updated.csv which contains new
3 min read
Convert CSV to Pandas Dataframe
In this article, we will discuss how to convert CSV to Pandas Dataframe, this operation can be performed using pandas.read_csv reads a comma-separated values (csv) file into DataFrame. Example 1: In the below program we are going to convert nba.csv into a data frame and then display it. Python Code # import pandas module import pandas as pd # makin
1 min read
How to Merge multiple CSV Files into a single Pandas dataframe ?
While working with CSV files during data analysis, we often have to deal with large datasets. Sometimes, it might be possible that a single CSV file doesn't consist of all the data that you need. In such cases, there's a need to merge these files into a single data frame. Luckily, the Pandas library provides us with various methods such as merge, c
3 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
How to check if a csv file is empty in pandas
Reading CSV (Comma-Separated Values) files is a common step in working with data, but what if the CSV file is empty? Python script errors and unusual behavior can result from trying to read an empty file. In this article, we'll look at methods for determining whether a CSV file is empty before attempting to read it. This will help you deal with the
4 min read
Reading specific columns of a CSV file using Pandas
CSV files are widely utilized for storing tabular data in file systems, and there are instances where these files contain extraneous columns that are irrelevant to our analysis. This article will explore techniques for selectively reading specific columns from a CSV file using Python. Let us see how to read specific columns of a CSV file using Pand
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
Practice Tags :