Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas read_excel() Method



Theread_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. Theread_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, orNone 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 includeopenpyxl (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), orxlrd (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 Pandasread_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 pandasread_excel() method with the local file.

import pandas as pd# Reading an excel filedf = pd.read_excel('car_excel.xlsx')# Display the output Data form excel fileprint("DataFrame from Excel File:")print(df)

When we run above program, it produces following result −

DataFrame from Excel File:
CarDate_of_purchase
0BMW2025-01-01
1Lexus2025-01-02
2Audi2025-01-07
3Mercedes2025-01-06
4Jaguar2025-01-09
5Bentley2025-01-22

Example: Reading Selected Columns from an Excel File

This example demonstrates reading specific columns from an excel file using the pandasread_excel() method with theusecols 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
0BMW
1Lexus
2Audi
3Mercedes
4Jaguar
5Bentley

Example: Specifying Data Types while reading Excel Data

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

import pandas as pd# Create a DataFramedata = {    "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 filedf.to_excel("example_data.xlsx", index=False)# Read the Excel file with specified data typesdf_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:
idteamscore
01.0Team A95
12.0Team B87
23.0Team C92
Column Data Types:id float64team string[python]score int64dtype: object

Example: Skipping Rows While Reading an Excel File

By using theskiprows 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 rowresult = 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:
Kiran25
0Charan30
1Riya35

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 thesheet_name parameter of theread_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 sheetsdata1 = {"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 sheetdf_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:
DepartmentLocation
0HRNew Delhi
1FinanceHyderabad
python_pandas_io_tool.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp