Pandas Read CSV

CSV stands for Comma-Separated Values. It is a popular file format used to store data in rows and columns. Pandas provides the read_csv() function to read CSV files and convert their data into a DataFrame. In this chapter, we will learn how to Pandas read CSV files and work with their contents.

1. What is a CSV File?

A CSV file is a text file that stores tabular data. Each line represents a row, and commas separate the values.

For example, consider the following student data:

students.csv

Name,Age,Marks
Rahul,18,85
Priya,19,90
Amit,18,75
Neha,20,95

This file contains three columns: Name, Age, and Marks.

Pandas can read this file and convert it into a DataFrame.

2. Reading a CSV File Using read_csv()

The read_csv() function is used to read a CSV file in Pandas.

Syntax:

pd.read_csv("filename.csv")

Example:

import pandas as pd

df = pd.read_csv("students.csv")

print(df)

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90
2   Amit   18     75
3   Neha   20     95

Explanation:

  • pd.read_csv() reads the CSV file.
  • "students.csv" is the name of the file.
  • Pandas converts the CSV data into a DataFrame.
  • print(df) displays the complete DataFrame.

Note: Keep the CSV file in the same folder as your Python program, or provide its correct file path.

3. Reading a CSV File Using Its File Path

Sometimes, a CSV file is stored in a different folder. In that case, you can provide the complete file path.

Example:

import pandas as pd

df = pd.read_csv("C:/Users/Admin/Documents/students.csv")

print(df)

Explanation:

  • The file path tells Pandas where the CSV file is stored.
  • Replace the example path with the actual location of your file.
  • Pandas reads the file and creates a DataFrame.

For Windows paths, forward slashes (/) are convenient to use in Python.

4. Displaying the First Five Rows Using head()

When a CSV file contains thousands of records, displaying the entire dataset can be difficult.

The head() method displays the first five rows by default.

Example:

import pandas as pd

df = pd.read_csv("students.csv")

print(df.head())

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90
2   Amit   18     75
3   Neha   20     95

Explanation:

  • head() displays the first five rows by default.
  • If the file contains fewer than five rows, it displays all available rows.
  • You can use it to quickly inspect the beginning of a dataset.

5. Displaying a Specific Number of Rows Using head()

You can provide a number inside head() to display a specific number of starting rows.

Example:

import pandas as pd

df = pd.read_csv("students.csv")

print(df.head(2))

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90

Explanation:

  • head(2) displays the first two rows.
  • You can change 2 to any number of rows you want to display.

6. Displaying the Last Five Rows Using tail()

The tail() method displays the last five rows of a DataFrame by default.

Example:

import pandas as pd

df = pd.read_csv("students.csv")

print(df.tail())

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90
2   Amit   18     75
3   Neha   20     95

Explanation:

  • tail() displays the last five rows by default.
  • If fewer than five rows are available, it displays all available rows.
  • It helps inspect the end of a dataset.

7. Displaying a Specific Number of Last Rows Using tail()

You can specify how many rows you want to display from the end of a DataFrame.

Example:

import pandas as pd

df = pd.read_csv("students.csv")

print(df.tail(2))

Output:

    Name  Age  Marks
2   Amit   18     75
3   Neha   20     95

Explanation:

  • tail(2) displays the last two rows.
  • This is useful for checking the latest records in a dataset.

8. Reading Specific Columns Using usecols

Sometimes, a CSV file contains many columns, but you only need a few of them.

The usecols parameter allows you to read selected columns.

Example:

import pandas as pd

df = pd.read_csv(
    "students.csv",
    usecols=["Name", "Marks"]
)

print(df)

Output:

    Name  Marks
0  Rahul     85
1  Priya     90
2   Amit     75
3   Neha     95

Explanation:

  • usecols specifies which columns should be read.
  • Only Name and Marks are included in the resulting DataFrame.
  • The Age column is excluded.

9. Reading a CSV File Without Headers

Sometimes, a CSV file does not contain column names in its first row.

You can use header=None to tell Pandas that the file has no header row.

Example:

students_no_header.csv

Rahul,18,85
Priya,19,90
Amit,18,75

Python Code:

import pandas as pd

df = pd.read_csv(
    "students_no_header.csv",
    header=None
)

print(df)

Output:

       0   1   2
0  Rahul  18  85
1  Priya  19  90
2   Amit  18  75

Explanation:

  • header=None tells Pandas that the CSV file does not have column names.
  • Pandas automatically assigns numeric column labels starting from 0.

10. Assigning Column Names to a CSV File Without Headers

If a CSV file does not contain column names, you can provide your own names using the names parameter.

Example:

import pandas as pd

df = pd.read_csv(
    "students_no_header.csv",
    header=None,
    names=["Name", "Age", "Marks"]
)

print(df)

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90
2   Amit   18     75

Explanation:

  • header=None indicates that the file has no header row.
  • names provides custom column names.
  • The resulting DataFrame uses the supplied column names.

11. Reading a CSV File with a Different Separator

CSV files usually use commas to separate values. However, some files use semicolons, tabs, or other separators.

You can use the sep parameter to specify the separator.

Example:

students_semicolon.csv

Name;Age;Marks
Rahul;18;85
Priya;19;90
Amit;18;75

Python Code:

import pandas as pd

df = pd.read_csv(
    "students_semicolon.csv",
    sep=";"
)

print(df)

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90
2   Amit   18     75

Explanation:

  • sep=";" tells Pandas that values are separated by semicolons.
  • Pandas uses the specified separator to identify columns.
  • This is useful when working with files that do not use commas.

12. Reading a CSV File Using nrows

The nrows parameter allows you to read only a specified number of rows from a CSV file.

Example:

import pandas as pd

df = pd.read_csv(
    "students.csv",
    nrows=2
)

print(df)

Output:

    Name  Age  Marks
0  Rahul   18     85
1  Priya   19     90

Explanation:

  • nrows=2 reads only the first two data rows.
  • The header row is still used for column names.
  • This is useful when you want to preview a large CSV file.

Student Task

Create a CSV file named employees.csv with the following data:

EmployeeID,Name,Department,Salary
101,Rahul,IT,35000
102,Priya,HR,40000
103,Amit,Sales,30000
104,Neha,IT,45000
105,Karan,Finance,50000

Complete these tasks:

  1. Read the CSV file using pd.read_csv().
  2. Display the complete DataFrame.
  3. Display the first three rows using head().
  4. Display the last two rows using tail().
  5. Read only the Name and Salary columns using usecols.
  6. Read only the first three data rows using nrows.
  7. Display the number of rows and columns using shape.

Key Takeaways

  • CSV stands for Comma-Separated Values.
  • pd.read_csv() reads CSV files into a DataFrame.
  • head() displays the first five rows by default.
  • tail() displays the last five rows by default.
  • usecols reads selected columns.
  • header=None reads files without column headers.
  • names assigns custom column names.
  • sep specifies the separator used in a file.
  • nrows limits the number of data rows read.

Frequently Asked Questions (FAQs)

1. How to Read CSV Files in Pandas?

You can use the pd.read_csv() function to read CSV files in Pandas. It loads CSV file data into a Pandas DataFrame, making it easy to analyze and manipulate data.

2. What is the Best Way to Read CSV in Pandas?

The easiest way to read CSV in Pandas is by using the read_csv() function. It supports different file paths, delimiters, column names, and missing values.

3. How to Read a CSV File in Python Using Pandas?

To read a CSV file in Python, first import the Pandas library using import pandas as pd. Then use pd.read_csv("filename.csv") to load the file into a DataFrame.

4. How to Import CSV in Python Without Opening It Manually?

You can import CSV in Python programmatically using the Pandas read_csv() function. Simply provide the CSV file name or its complete file path.

5. What is the Use of the Pandas Read CSV Function?

The Pandas Read CSV function is used to load tabular data from CSV files into a DataFrame. It helps developers read, organize, filter, and analyze datasets.

6. Can We Read a Large CSV File Using Pandas?

Yes, Pandas can read large CSV files. You can use the chunksize parameter in pd.read_csv() to load and process data in smaller portions.

7. How to Read a CSV File from a Specific Folder in Python?

You can read a CSV file from a specific folder by providing its complete file path inside pd.read_csv(). This allows Pandas to access files stored in different directories.

8. Why Should Beginners Learn a Pandas CSV Tutorial?

A Pandas CSV Tutorial helps beginners understand how to import, read, and manage CSV files using Python. These skills are essential for data analysis, data cleaning, and working with real-world datasets.

9. How to Read CSV in Pandas Without Column Headers?

You can read a CSV file without column headers using the header=None parameter in pd.read_csv(). Pandas will automatically assign default column names, such as 0, 1, 2, and so on.

10. How to Import and Convert a CSV File into a Pandas DataFrame in Python?

You can import a CSV file in Python using pd.read_csv("filename.csv"). This Pandas Read CSV method automatically converts the CSV data into a DataFrame, allowing you to perform data analysis, filtering, and manipulation easily.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top