Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Pandas read_excel() Method



The read_excel() method in Python's Pandas library allows you to read or load data from an Excel file into a Pandas DataFrame. This method supports multiple Excel file formats, including .xlsx, .xlsb, and .xls. It also provides options for reading specific sheets, parsing dates, and more. This method is highly flexible for handling structured data, widely used in data analysis tasks.

Excel is a popular spreadsheet format for storing tabular data. It provides features like multiple sheets and rich formatting. The read_excel() method simplifies importing Excel data into Pandas for analysis and processing. It supports reading data from a local file system or URL and supports both single and multiple sheets.

Syntax

The syntax of the read_excel() method is as follows −

pandas.read_excel(io, sheet_name=0, *, header=0, names=None, index_col=None, usecols=None, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, parse_dates=False, date_parser=<no_default>, date_format=None, thousands=None, decimal='.', comment=None, skipfooter=0, storage_options=None, dtype_backend=<no_default>, engine_kwargs=None)

Parameters

The Python Pandas read_excel() method accepts the below parameters −

  • io: The file path, URL, or file-like object to read Excel file from. Supports various schemes like http, ftp, s3, etc.

  • sheet_name: Specifies the sheet/sheets to read. It can be an integer (representing the sheet index), string (represents sheet name), a list, or None to read all sheets.

  • header: Specifies the row number to use as column names. By default it is set to 0, meaning Pandas will attempt to detect the header row automatically.

  • names: A list of column names to use when there is no header row. If the file contains a header row, you can override it by specifying custom column names.

  • index_col: Specifies a column (or multiple columns) to set as the DataFrame index.

  • usecols: Specifies which columns to load.

  • dtype: Defines the data type of columns.

  • engine: It specifies the parser engine to use. Options include openpyxl (for newer Excel file formats), calamine (supports Excel .xls, .xlsx, .xlsm, .xlsb and .ods), odf (for OpenDocument file formats .odf, .ods, .odt), pyxlsb (for supporting Binary Excel files), or xlrd (for supporting old-style Excel files).

  • converters: This parameter takes a function or a dictionary of functions for converting values in specified columns.

  • true_values and false_values: Values to consider as True and False, in addition to case-insensitive True and False.

  • skiprows: Skips the specified number of rows at the start.

  • nrows: Specifies number of rows to read.

  • na_values: Additional strings to recognize as NaN.

  • keep_default_na: Include default NaN values for missing data.

  • na_filter: Detect missing value markers. Improves performance for files without missing data.

  • parse_dates: Attempts to parse the specified columns as dates.

  • date_parser: Custom date parser function.

  • storage_options: Extra options related to storage connections.

  • Others: It includes additional parameters to fine-tune the parsing behavior of Excel data into Pandas.

Return Value

The Pandas read_excel() method returns a Pandas DataFrame containing the data from the Excel file.

Example: Reading a Simple Excel File

Here is a basic example demonstrating reading a simple Excel file using the pandas read_excel() method with the local file.

import pandas as pd

# Reading an excel file
df = pd.read_excel('car_excel.xlsx')

# Display the output Data form excel file
print("DataFrame from Excel File:")
print(df)

When we run above program, it produces following result −

DataFrame from Excel File:
Car Date_of_purchase
0 BMW 2025-01-01
1 Lexus 2025-01-02
2 Audi 2025-01-07
3 Mercedes 2025-01-06
4 Jaguar 2025-01-09
5 Bentley 2025-01-22

Example: Reading Selected Columns from an Excel File

This example demonstrates reading specific columns from an excel file using the pandas read_excel() method with the usecols parameter.

import pandas as pd

# read specified columns from an Excel file into a Pandas DataFrame 
df = pd.read_excel('car_excel.xlsx', usecols=["Car"])

print("Reading Specific Columns from an excel File:")
print(df.head())

While executing the above code we get the following output −

Reading Specific Columns from an excel File:
Car
0 BMW
1 Lexus
2 Audi
3 Mercedes
4 Jaguar
5 Bentley

Example: Specifying Data Types while reading Excel Data

The read_excel() method allows you to specify the data type to the columns while reading data from an excel file using the dtype parameter.

import pandas as pd

# Create a DataFrame
data = {
    "id": [1, 2, 3],
    "team": ["Team A", "Team B", "Team C"],
    "score": [95, 87, 92]
}
df = pd.DataFrame(data)

# Write the DataFrame to an Excel file
df.to_excel("example_data.xlsx", index=False)

# Read the Excel file with specified data types
df_read = pd.read_excel("example_data.xlsx", dtype={"id": "float", "team": "string"})

print("DataFrame from Excel with Specified Data Types:")
print(df_read)

print("\nColumn Data Types:")
print(df_read.dtypes)

Following is an output of the above code −

DataFrame from EXcel with Specified Data Types:
id team score
0 1.0 Team A 95
1 2.0 Team B 87
2 3.0 Team C 92
Column Data Types: id float64 team string[python] score int64 dtype: object

Example: Skipping Rows While Reading an Excel File

By using the skiprows parameter you can skip unnecessary rows from the Excel file and convert data into Pandas DataFrame.

import pandas as pd

# Create an Excel file 
data = {
"Name": ["Kiran", "Charan", "Riya"],
"Age": [25, 30, 35],
}

df = pd.DataFrame(data)
df.to_excel("data_excel_file.xlsx", index=False)

# Read Excel data by skipping the first row
result = pd.read_excel("data_excel_file.xlsx", skiprows=1)

print("DataFrame from Excel File:")
print(result)

When we run above program, it produces following result −

DataFrame from Excel File:
Kiran 25
0 Charan 30
1 Riya 35

Example: Reading Data from a Specific Sheet of an Excel File

You can read data from a specific sheet of a multi sheet Excel file by using the sheet_name parameter of the read_excel() method. In the following example, we first create an Excel file with two sheets and then read data from the second sheet. the data from 2nd sheet.

import pandas as pd

# Create a sample Excel file with multiple sheets
data1 = {"Name": ["Kiran", "Priya"], "Age": [25, 30]}
data2 = {"Department": ["HR", "Finance"], "Location": ["New Delhi", "Hyderabad"]}

with pd.ExcelWriter("multi_sheet_example.xlsx") as writer:
    pd.DataFrame(data1).to_excel(writer, sheet_name="Sheet1", index=False)
    pd.DataFrame(data2).to_excel(writer, sheet_name="Sheet2", index=False)

# Read data from a specific sheet
df_sheet2 = pd.read_excel("multi_sheet_example.xlsx", sheet_name="Sheet2")

print("Data from Sheet2:")
print(df_sheet2)

Following is an output of the above code −

Data from Sheet2:
Department Location
0 HR New Delhi
1 Finance Hyderabad
python_pandas_io_tool.htm
Advertisements