Pandas Excel File Operations
Pandas provides rich Excel file operation features, helping us easily read and write .xls and .xlsx files, supporting complex operations such as multiple sheets, indexes, and column selection; it is an essential tool in data analysis.
| Operation | Method | Description |
|---|---|---|
| Read Excel files | pd.read_excel() |
Read an Excel file, returning a DataFrame |
| Write a DataFrame to Excel | DataFrame.to_excel() |
Write a DataFrame to an Excel file |
| Load an Excel file | pd.ExcelFile() |
Load an Excel file and access multiple sheets |
| Write multiple sheets with ExcelWriter | pd.ExcelWriter() |
Write multiple DataFrames to different sheets of the same Excel file |
pd.read_excel() - 读取 Excel 文件
pd.read_excel() method is used to read data from an Excel file and load it as a DataFrame. It supports reading .xls and .xlsx format files.
The syntax format 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=, date_format=None, thousands=None, decimal='.', comment=None, skipfooter=0, storage_options=None, dtype_backend= , engine_kwargs=None)
Parameter Description:
-
io: This is a required parameter that specifies the path or file object of the Excel file to read. -
sheet_name=0: Specifies the name or index of the worksheet to read. The default is 0, meaning the first worksheet. -
header=0: Specifies the row to use as column names. The default is 0, meaning the first row. -
names=None: A list used to specify column names. If provided, it overrides the column names in the file. -
index_col=None: Specifies the column to use as the row index. It can be a column name or a number. -
usecols=None: Specifies the columns to read. It can be a list of column names or a list of column indexes. -
dtype=None: Specifies the data types of columns. It can be a dictionary with column names as keys and data types as values. -
engine=None: Specifies the parsing engine. The default isNone, and pandas will select one automatically. -
converters=None: A dictionary of functions for converting data. -
true_values=None: Specifies values that should be treated as booleansTruevalue. -
false_values=None: Specifies values that should be treated as booleansFalsevalue. -
skiprows=None: Specifies the number of rows to skip or a list of rows to skip. -
nrows=None: Specifies the number of rows to read. -
na_values=None: Specifies values that should be treated as missing values. -
keep_default_na=True: Specifies whether to treat default missing values (such asNaN) asNA。 -
na_filter=True: Specifies whether to convert data toNA。 -
verbose=False: Specifies whether to output detailed progress information. -
parse_dates=False: Specifies whether to parse dates. -
date_parser=: A function for parsing dates. -
date_format=None: Specifies the date format. -
thousands=None: Specifies the thousands separator. -
decimal='.': Specifies the decimal point character. -
comment=None: Specifies the comment character. -
skipfooter=0: Specifies the number of lines to skip at the end of the file. -
storage_options=None: A dictionary of parameters for cloud storage. -
dtype_backend=: Specifies the data type backend. -
engine_kwargs=None: A dictionary of extra parameters passed to the engine.
This article takes runoob_pandas_data.xlsx as an example; you canDownload runoob_pandas_data.xlsx to test.
Example
# Read the data.xlsx file
df = pd.read_excel('runoob_pandas_data.xlsx')
# Print the DataFrame that was read
print(df)
The output is:
表格 1 Unnamed: 1 Unnamed: 2 0 Name Age City 1 Alice 25 New York 2 Bob 30 Los Angeles 3 Charlie 35 Chicago
read_excel reads the first sheet by default (sheet_name=0). Assuming the data.xlsx file has only one sheet, the read data is stored in a DataFrame.
If the data.xlsx file has multiple sheets, you can read data from a specific sheet by specifying sheet_name, for example pd.read_excel('data.xlsx', sheet_name='Sheet1')。
Example
# Read the default first sheet
df = pd.read_excel('data.xlsx')
print(df)
# Read the contents of a specified sheet (by sheet name)
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(df)
# Read multiple sheets, returning a dictionary
dfs = pd.read_excel('data.xlsx', sheet_name=['Sheet1', 'Sheet2'])
print(dfs)
# Customize column names and skip the first two rows
df = pd.read_excel('data.xlsx', header=None, names=['A', 'B', 'C'], skiprows=2)
print(df)
DataFrame.to_excel() - Write a DataFrame to an Excel file
to_excel() method is used to write a DataFrame to an Excel file and supports .xls and .xlsx format.
The syntax format is as follows:
DataFrame.to_excel(excel_writer, *, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, inf_rep='inf', freeze_panes=None, storage_options=None, engine_kwargs=None)
Parameter Description:
-
excel_writer: This is a required parameter that specifies the path or file object of the Excel file to write to. -
sheet_name='Sheet1': Specifies the name of the worksheet to write; the default is'Sheet1'。 -
na_rep='': Specifies the string used to represent missing values (NaN) in the Excel file; the default is an empty string. -
float_format=None: Specifies the format for floating-point numbers. If it isNone, Excel's default format is used. -
columns=None: Specifies the columns to write. If it isNone, all columns are written. -
header=True: Specifies whether to write column names as the first row. If it isFalse, column names are not written. -
index=True: Specifies whether to write the index as the first column. If it isFalse, the index is not written. -
index_label=None: Specifies the label of the index column. If it isNone, the index label is not written. -
startrow=0: Specifies the row number at which to start writing; the default is row 0. -
startcol=0: Specifies the column number at which to start writing; the default is column 0. -
engine=None: Specifies the engine used when writing the Excel file; the default isNone, and pandas will select one automatically. -
merge_cells=True: Specifies whether to merge cells. If it isTrue, cells with the same value are merged. -
inf_rep='inf': Specifies the string used to represent infinite values in the Excel file; the default is'inf'。 -
freeze_panes=None: Specifies the position of frozen panes. If it isNone, no panes are frozen. -
storage_options=None: A dictionary of parameters for cloud storage. -
engine_kwargs=None: A dictionary of extra parameters passed to the engine.
Example
# Create a simple DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
# Write the DataFrame to an Excel file, into the 'Sheet1' sheet
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)
# Write multiple sheets using ExcelWriter
with pd.ExcelWriter('output.xlsx') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.to_excel(writer, sheet_name='Sheet2', index=False)
ExcelFile - Load an Excel file
ExcelFile is a class for reading Excel files; it can handle multiple sheets and access their data without reopening the file.
The syntax format is as follows:
excel_file = pd.ExcelFile('data.xlsx')
Common methods:
| Method | Description |
|---|---|
sheet_names |
Return a list of the names of all sheets in the file |
parse(sheet_name) |
Parse a specified sheet and return a DataFrame |
close() |
Close the file to release resources |
Example
# Load an Excel file using ExcelFile
excel_file = pd.ExcelFile('data.xlsx')
# View the names of all sheets
print(excel_file.sheet_names)
# Read a specified sheet
df = excel_file.parse('Sheet1')
print(df)
# Close the file
excel_file.close()
ExcelWriter - Write Excel files
ExcelWriter is a class provided by pandas for writing DataFrame or Series objects to Excel files. With ExcelWriter, you can write multiple worksheets into a single Excel file and control the writing process more flexibly.
The syntax format is as follows:
pandas.ExcelWriter(path, engine=None, date_format=None, datetime_format=None, mode='w', storage_options=None, if_sheet_exists=None, engine_kwargs=None)
Parameter Description:
-
path: This is a required parameter that specifies the path, URL, or file object of the Excel file to write to. It can be a local file path, a remote storage path (such as S3), a URL link, or an already-open file object 。 -
engine: This is an optional parameter that specifies the engine used to write the Excel file. If it isNone, pandas automatically selects an available engine (by default it prefersopenpyxl; if unavailable, another available engine is chosen). Common engines include'openpyxl'(for.xlsxfiles),'xlsxwriter'(providing advanced formatting and chart features),'odf'(for OpenDocument formats such as.ods) and others 。 -
date_format: An optional parameter that specifies the format string for dates written to the Excel file, for example"YYYY-MM-DD"。 -
datetime_format: An optional parameter that specifies the format string for datetime objects written to the Excel file, for example"YYYY-MM-DD HH:MM:SS"。 -
mode: An optional parameter whose default is'w', indicating write mode. If set to'a', it means append mode, adding data to an existing file (supported only by some engines, such asopenpyxl) 。 -
storage_options: An optional parameter that specifies extra options for connecting to the storage backend, such as authentication information and access permissions; it applies to writing to remote storage (such as S3 or GCS) 。 -
if_sheet_exists: An optional parameter whose default is'error', specifying the behavior when a worksheet already exists. Options include'error'(raise an error),'new'(create a new worksheet),'replace'(replace the contents of the existing worksheet),'overlay'(overwrite on the existing worksheet) 。 -
engine_kwargs: An optional parameter for passing other keyword arguments to the engine. These arguments are passed to the corresponding engine's functions, for examplexlsxwriter.Workbook(file, **engine_kwargs)oropenpyxl.Workbook(**engine_kwargs)etc. 。
Create an ExcelWriter object:
Example
df.to_excel(writer, sheet_name='Sheet1')
Here, ExcelWriter is used as a context manager to ensure the file is properly closed after the operation completes.
Write multiple worksheets:
You can use the same ExcelWriter object to write different DataFrames to different worksheets of the same Excel file.
Example
df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
with pd.ExcelWriter("path_to_file.xlsx") as writer:
df1.to_excel(writer, sheet_name="Sheet1")
df2.to_excel(writer, sheet_name="Sheet2")
Set date or datetime formats:
Example
df = pd.DataFrame(
[
[date(2014, 1, 31), date(1999, 9, 24)],
[datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
],
index=["Date", "Datetime"],
columns=["X", "Y"],
)
with pd.ExcelWriter(
"path_to_file.xlsx",
date_format="YYYY-MM-DD",
datetime_format="YYYY-MM-DD HH:MM:SS"
) as writer:
df.to_excel(writer)
Append content to an existing Excel file:
Example
df.to_excel(writer, sheet_name="Sheet3")
Use the if_sheet_exists parameter to replace an existing worksheet:
Example
"path_to_file.xlsx",
mode="a",
engine="openpyxl",
if_sheet_exists="replace",
) as writer:
df.to_excel(writer, sheet_name="Sheet1")
Write multiple DataFrames to the same worksheet; note that the if_sheet_exists parameter must be set to overlay:
Example
mode="a",
engine="openpyxl",
if_sheet_exists="overlay",
) as writer:
df1.to_excel(writer, sheet_name="Sheet1")
df2.to_excel(writer, sheet_name="Sheet1", startcol=3)
Store an Excel file in memory:
Example
df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
buffer = io.BytesIO()
with pd.ExcelWriter(buffer) as writer:
df.to_excel(writer)
Package an Excel file into a zip archive:
Example
df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
with zipfile.ZipFile("path_to_file.zip", "w") as zf:
with zf.open("filename.xlsx", "w") as buffer:
with pd.ExcelWriter(buffer) as writer:
df.to_excel(writer)
Pass extra parameters to the underlying engine:
Example
"path_to_file.xlsx",
engine="xlsxwriter",
engine_kwargs={"options": {"nan_inf_to_errors": True}}
) as writer:
df.to_excel(writer)
In append mode, engine_kwargs is passed to openpyxl's load_workbook:
Example
"path_to_file.xlsx",
engine="openpyxl",
mode="a",
engine_kwargs={"keep_vba": True}
) as writer:
df.to_excel(writer, sheet_name="Sheet2")