The Wayback Machine - https://web.archive.org/web/20240913092614/https://www.geeksforgeeks.org/how-to-import-an-excel-file-into-python-using-pandas/
Open In App

How to import an excel file into Python using Pandas?

Last Updated : 17 Aug, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a ‘.xlsx’ format. 

Before we get started,  we need to install a few libraries. 

pip install pandas
pip install xlrd

 For importing an Excel file into Python using Pandas we have to use pandas.read_excel() function.

Syntax: pandas.read_excel(io, sheet_name=0, header=0, names=None,….)

Return: DataFrame or dict of DataFrames.

Let’s suppose the Excel file looks like this:

Excel file

Now, we can dive into the code. 

Example 1: Read an Excel file.

Python3




import pandas as pd
  
df = pd.read_excel("sample.xlsx")
print(df)


Output:

dataframe

Example 2: To select a particular column, we can pass a parameter “index_col“. 

Python3




import pandas as pd
  
# Here 0th column will be extracted
df = pd.read_excel("sample.xlsx",
                   index_col = 0)  
  
print(df)


Output:

select a particular column

Example 3: In case you don’t prefer the initial heading of the columns, you can change it to indexes using the parameter “header”.

Python3




import pandas as pd
  
df = pd.read_excel('sample.xlsx',
                   header = None)
print(df)


Output:

dataframe without header

Example 4: If you want to change the data type of a particular column you can do it using the parameter “dtype“.

Python3




import pandas as pd
  
df = pd.read_excel('sample.xlsx', 
                   dtype = {"Products": str,
                            "Price":float})
print(df)


Output:

data type change

Example 5: In case you have unknown values, then you can handle it using the parameter “na_values“. It will convert the mentioned unknown values into “NaN” 

Python3




import pandas as pd
df = pd.read_excel('sample.xlsx', 
                   na_values =['item1', 
                               'item2'])
print(df)


Output:

Dataframe with NaN value



Similar Reads

How to import excel file and find a specific column using Pandas?
To read specific columns from an Excel file in Pandas, you have the flexibility to use either column indices or letters. This is achieved by setting the usecols argument, which can take a comma-separated string or a list containing column identifying letters or indices. In this article, we will learn how to import an Excel file into a data frame an
5 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
Different ways to import csv file in Pandas
CSV files are the "comma separated values", these values are separated by commas, this file can be viewed as an Excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can be in CSV file format. Let's see the different ways to import csv files in
3 min read
How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 min read
How to extract Time data from an Excel file column using Pandas?
Prerequisite: Regular Expressions in Python In these articles, we will discuss how to extract Time data from an Excel file column using Pandas. Suppose our Excel file looks like below given image then we have to extract the Time from the Excel sheet column and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach: Im
2 min read
How to extract Email column from Excel file and find out the type of mail using Pandas?
In this article, Let's see how to Extract Email column from an Excel file and find out the type of mail using Pandas. Suppose our Excel file looks like below given image, and then we have to store different type of emails in different columns of Dataframe. For viewing the Excel file Click Here Approach: Import required module.Import data from Excel
3 min read
How to extract date from Excel file using Pandas?
Prerequisite: Regular Expressions in Python In this article, Let's see how to extract date from the Excel file. Suppose our Excel file looks like below given image then we have to extract the date from the string and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach : Import required module.Import data from Excel
3 min read
Find the sum and maximum value of the two column in excel file using Pandas
In these articles, we will discuss how to read data from excel and perform some mathematical operation and store it into a new column in DataFrame. Suppose our excel file looks like this. Then we have to compute the sum of two-column and find out the maximum value and store into a new DataFrame column. Approach : Import Pandas module.Read data from
2 min read
How to import JSON File in MongoDB using Python?
Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
2 min read
How to import CSV file in SQLite database using Python ?
In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. Approach: Importing necessary modulesRead data from CSV file DictReader()Establish a connection with the database.sqlit
2 min read
Combine Multiple Excel Worksheets Into a Single Pandas Dataframe
Prerequisites: Working with excel files using Pandas In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let's suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file. Approach : Import-ModuleRe
1 min read
Exporting a Pandas DataFrame to an Excel file
Sometimes we need an Excel file for reporting, so as a coder we will see how to export Pandas DataFrame to an Excel file. The to_excel() function in the Pandas library is utilized to export a DataFrame to an Excel sheet with the .xlsx extension. By default, it saves a single DataFrame to an Excel file. However, the capability to write multiple shee
5 min read
Python - Import CSV into PostgreSQL
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the "creat
2 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
How to import a class from another file in Python ?
In this article, we will see How to import a class from another file in Python. Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole
4 min read
PyMongoArrow: Export and Import MongoDB data to Pandas DataFrame and NumPy
If you are a data scientist or a Python developer who sometimes wears the data scientist hat, it is highly likely that at some point you were required to work with these three tools & technologies: Pandas, NumPy and MongoDB. Pandas: Pandas is a fast, powerful and easy-to-use open-source data analysis and manipulation tool, built on top of the P
8 min read
Import Text Files Into Numpy Arrays
Numpy is an acronym for 'Numerical Python'. It is a library in python for supporting n-dimensional arrays. But have you ever wondered about loading data into NumPy from text files. Don't worry we will discuss the same in this article. To import Text files into Numpy Arrays, we have two functions in Numpy: numpy.loadtxt( ) - Used to load text file d
3 min read
How to Import Kaggle Datasets Directly into Google Colab
In this article, we will see how to import Kaggle Datasets into Google Colab. Getting Started Here, we are going to cover two different methods to start working with Colab. In the first method, we will use Kaggle API to download our dataset, and after that, we are good to go to use our dataset. In another method, we manually download from the Kaggl
3 min read
Create an Import File Button with Tkinter
Graphical User Interfaces (GUIs) play a crucial role in enhancing the user experience of applications. Tkinter, a built-in Python library, provides a simple way to create GUI applications. In this article, we will focus on creating an "Import File" button using Tkinter. Create An Import File Button With TkinterIn this section, we will create an imp
3 min read
How to Extract and Import file in Django
In Django, extracting and importing files is a common requirement for various applications. Whether it's handling user-uploaded files, importing data from external sources, or processing files within your application, Django provides robust tools and libraries to facilitate these tasks. This article explores techniques and best practices for extrac
4 min read
How to Import a JSON File to a Django Model?
In many web development projects, it's common to encounter the need to import data from external sources into a Django application's database. This could be data obtained from APIs, CSV files, or in this case, JSON files. JSON (JavaScript Object Notation) is a popular format for structuring data, and integrating it into a Django project can be quit
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
Joining Excel Data from Multiple files using Python Pandas
Let us see how to join the data of two excel files and save the merged data as a new Excel file. We have 2 files, registration details.xlsx and exam results.xlsx. registration details.xlsx We are having 7 columns in this file with 14 unique students details. Column names are as follows : Admission Date Name of Student Gender DOB Student email Id En
2 min read
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python?
The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method. Syntax: pandas.pivot_table(data, index=None) Parameters: data : DataFrame index: column, Grouper, array, or list of the previous index: It is the feature that allows you to group
2 min read
How to load a TSV file into a Pandas DataFrame?
In this article, we will discuss how to load a TSV file into a Pandas Dataframe. The idea is extremely simple we only have to first import all the required libraries and then load the data set by using various methods in Python. Dataset Used: data.tsv Using read_csv() to load a TSV file into a Pandas DataFrame Here we are using the read_csv() metho
1 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Python | Arithmetic operations in excel file using openpyxl
Prerequisite: Reading & Writing to excel sheet using openpyxlOpenpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to perform different arithmetic operations using openpyxl. =SUM(cell1:cell2) : Adds all the numbers in a range of
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Trigonometric operations in excel file using openpyxl
Prerequisite : Adjusting rows and columns of an excel sheet using openpyxl. Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, mathematical operations and plotting graphs. Let’s see how to perform different Trigonometric operations using openpyxl. Simple trigonometric functions : Code
3 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
Practice Tags :