Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.read_excel() function

Pandas pd.read_excel() function

Python math Module Common Pandas functions


read_excel() is a function in the pandas library for reading Excel files; it supports .xlsx and .xls format Excel files.

Excel is the most commonly used file format in enterprise data analysis; it supports multiple worksheets, rich cell formatting, formulas, and more.read_excel() can read data from Excel files and convert it into a pandas DataFrame, making subsequent processing and analysis convenient.


Basic syntax and parameters

Syntax format



pandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None,

                 usecols=None, dtype=None, skiprows=None, nrows=None,

                 na_values=None, ...)

Parameter Description

Parameters Type Description Default value
io str, ExcelFile, path object, file-like object the Excel file path or an ExcelFile object Required
sheet_name str, int, list, None the name or index of the worksheet to read; None reads all worksheets 0
header int, list of int the row number to use as column names; 0 means the first row 0
names list-like a custom list of column names None
index_col int, str Column used as the row index None
usecols int, str, list read only the specified columns None
dtype dict specify the data types of columns None
skiprows list-like, int skip the specified rows None
nrows int read only the first n rows None

Return Value


Example

Through the following examples, fully master read_excel() its various usages.

Example 1: read a local Excel file

First, create and read a simple Excel file.

Example

import

pandas

as

pd

import

openpyxl  

Need to install: pip install openpyxl

Create a DataFrame

data

=

{

   

'name'

:

[

'Tom'

,

'Jerry'

,

'Mike'

,

'Lucy'

]

,

   

'age'

:

[

28

,

35

,

42

,

26

]

,

   

'city'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

,

   

'salary'

:

[

8000

,

12000

,

15000

,

7000

]

}

df_original

=

pd.

DataFrame

(

data

)

Write a DataFrame to an Excel file

Excel file path: employees.xlsx

df_original.

to_excel

(

'employees.xlsx'

,

index

=

False

,

engine

=

'openpyxl'

)

Read the Excel file using read_excel

io: file path (required)

df

=

pd.

read_excel

(

'employees.xlsx'

)

View the reading result

print

(

"DataFrame read:"

)

print

(

df

)

print

(

"ndata types:"

)

print

(

df.

dtypes

)

Expected output:



读取的 DataFrame:

    name  age       city  salary

0    Tom   28    Beijing    8000

1  Jerry   35   Shanghai   12000

2   Mike   42   Guangzhou   15000

3  Lucy   26   Shenzhen    7000



Data type:

name      object

age        int64

city      object

salary    int64

Code analysis:

Example 2: read multiple worksheets

An Excel file can contain multiple worksheets,read_excel() supports flexibly reading specified worksheets or all worksheets.

h2 class="example">Example

import

pandas

as

pd

Create an Excel file containing multiple worksheets

First create two DataFrames

df_sales

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'C'

,

'D'

]

,

   

'quantity'

:

[

100

,

200

,

150

,

80

]

,

   

'price'

:

[

50

,

30

,

40

,

60

]

}

)

df_inventory

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'C'

,

'D'

]

,

   

'stock'

:

[

500

,

300

,

400

,

200

]

,

   

'warehouse'

:

[

'WH1'

,

'WH2'

,

'WH1'

,

'WH3'

]

}

)

Write multiple worksheets to one Excel file

with

pd.

ExcelWriter

(

'multi_sheet.xlsx'

,

engine

=

'openpyxl'

)

as

writer:

    df_sales.

to_excel

(

writer

,

sheet_name

=

'Sales'

,

index

=

False

)

    df_inventory.

to_excel

(

writer

,

sheet_name

=

'Inventory'

,

index

=

False

)

Example 2a: read a specified worksheet (by name)

df_sales_read

=

pd.

read_excel

(

'multi_sheet.xlsx'

,

sheet_name

=

'Sales'

)

print

(

"read the Sales worksheet:"

)

print

(

df_sales_read

)

print

(

)

Example 2b: read a specified worksheet (by index)

df_inv_read

=

pd.

read_excel

(

'multi_sheet.xlsx'

,

sheet_name

=

1

)

print

(

"read the 2nd worksheet (index 1):"

)

print

(

df_inv_read

)

print

(

)

Example 2c: read all worksheets (returns a dictionary)

all_sheets

=

pd.

read_excel

(

'multi_sheet.xlsx'

,

sheet_name

=

None

)

print

(

"all worksheet names:"

,

list

(

all_sheets.

keys

(

)

)

)

print

(

"niterate over all worksheets:"

)

for

sheet_name

,

df_sheet

in

all_sheets.

items

(

)

:

   

print

(

f

"n--- {sheet_name} ---"

)

   

print

(

df_sheet

)

Expected output:



Read Sales worksheet:

  product  quantity  price

0       A       100     50

1       B       200     30

2       C       150     40

3       D        80     60



读取第2个工作表 (索引为1):

  product  stock warehouse

0       A    500       WH1

1       B    300       WA2

2       C    400       WH1

3       D    200       WH3



所有工作表名称: ['Sales', 'Inventory']



Iterate through all worksheets:

--- Sales ---

  product  quantity  price

...



--- Inventory ---

  product  stock warehouse

...

Code analysis:

Example 3: advanced usage - custom columns and skipped rows

In real work, Excel files may have complex formats that need flexible handling.

Example

import

pandas

as

pd

Create an Excel file with title rows and blank rows

The first few rows are metadata; the actual data starts from row 4

data_with_header

=

"""company employee data
Created: 2024-01-01
Department: Engineering

name,age,city,salary
Tom,28,Beijing,8000
Jerry,35,Shanghai,12000
"""

First create a CSV and then convert it to Excel (simulating a real scenario)

import

io

df_temp

=

pd.

read_csv

(

io.

StringIO

(

data_with_header.

split

(

'---'

)

[

1

]

)

)

df_temp.

to_excel

(

'complex_format.xlsx'

,

index

=

False

,

engine

=

'openpyxl'

)

Example 3a: skip the first few rows and use row N as column names

df_skip

=

pd.

read_excel

(

'complex_format.xlsx'

,

header

=

3

)

print

(

"skip the first 3 rows and use row 4 as column names:"

)

print

(

df_skip

)

print

(

)

Example 3b: read only the specified columns

df_cols

=

pd.

read_excel

(

'complex_format.xlsx'

,

usecols

=

[

'name'

,

'salary'

]

)

print

(

"read only the name and salary columns:"

)

print

(

df_cols

)

print

(

)

Example 3c: read only the first few rows

df_head

=

pd.

read_excel

(

'complex_format.xlsx'

,

nrows

=

2

)

print

(

"read only the first 2 rows:"

)

print

(

df_head

)

print

(

)

Example 3d: custom column names

df_custom_names

=

pd.

read_excel

(

'complex_format.xlsx'

,

                                  names

=

[

'Name'

,

'Age'

,

'City'

,

'Salary'

]

,

                                  header

=

0

)

print

(

"custom column names:"

)

print

(

df_custom_names

)

Expected output:



Skip the first 3 lines, use the 4th line as column names:

    name  age     city  salary

0    Tom   28  Beijing    8000

1  Jerry   35  Shanghai  12000



# Only read name and salary columns:

    name  salary

0    Tom    8000

1  Jerry  12000



Only read the first 2 lines:

    name  age     city  salary

0    Tom   28  Beijing    8000



Custom column name:

     姓名  年龄       城市    薪资

0    Tom   28    Beijing   8000

1  Jerry   35   Shanghai  12000

Code analysis:


Notes


Summary

read_excel() is the core function in pandas for reading Excel files and is very powerful. It supports reading single or multiple worksheets and can flexibly handle Excel files in various formats.

In real data analysis work, Excel files are one of the most common data sources. Becoming proficient with read_excel() and its various parameters lets you efficiently handle all kinds of Excel data and prepare for subsequent cleaning and analysis. Readers are encouraged to practice more, especially reading multiple worksheets and configuring parameters.

Python math Module Common Pandas functions