How to Import Excel File in Python Using Pandas


Import Excel File in Python Using Pandas

Importing Excel File in Python is one of the easiest tasks using pandas. In this tutorial, you are going to learn how to Import Excel File in Python Using Pandas.

Before you start

Install xlrd package to read excel file using pip package installer otherwise you may get the error:

Note: If you don’t have installed pip then install it by using this tutorial.

pip install xlrd

Basic Syntax to Import Excel File

In this tutorial to import excel file, we are going to use read_excel() function of pandas library. Following is the basic syntax for read_excel() function:

df = pd.read_excel(r'PATH_OF_THE_EXCEL_FILE\FILE_NAME.xlsx')

and if you want to import a specific sheet then:

df = pd.read_excel(r'PATH_OF_THE_EXCEL_FILE\FILE_NAME.xlsx', 'SHEET_NAME')

Where,
PATH_OF_THE_EXCEL_FILE: Path of the excel file where it is located.
FILE_NAME: Name of the excel file.
SHEET_NAME: Name of the specific sheet.

Example Programs to Import Excel File

Assume your excel file is located at C:\Users\CrazyGeeks\Documents\Students.xlsx. The data of the file is given below:

Name Marks
John 85
Sarah 91
Nick 78
Jack 60
Alan 91

1. Import Excel File in Pandas

Now to import above excel file using read_excel() function of the pandas the library you can use the following program:

import pandas as pd

# Don't forget to use "r" before the path string. It is used to address special characters. 
df = pd.read_excel(r'C:\Users\CrazyGeeks\Documents\Students.xlsx')
print(df)

The output should be:

"How

2. Import Specific Sheet of Excel File

If you have sheet name Sheet1 inside file Students.xlsx then you can import such a sheet by using the following code:

import pandas as pd

# Don't forget to use "r" before the path string. It is used to address special characters. 
df = pd.read_excel(r'C:\Users\CrazyGeeks\Documents\Students.xlsx','Sheet1')
print(df)

The output should be:

"How

3. Import Specific Column of Excel File

You can also import a specific column from the excel sheet. To import column only you can use

import pandas as pd

# Don't forget to use "r" before the path string. It is used to address special characters. 
df = pd.read_excel(r'C:\Users\CrazyGeeks\Documents\Students.xlsx')
df = pd.DataFrame(df, columns= ['Name'])
print(df)

The output should be:

"How

Conclusion

You have successfully learned How to Import Excel File in Python Using Pandas. If you have queries regarding this tutorial please do not forget to comment below.