目录

13.-Pandas-使用-to_excel-方法写入-Excel文件

13. Pandas :使用 to_excel 方法写入 Excel文件

一 to_excel 方法的相关参数

用它来指定要将 DataFrame 写入哪些工作表的哪些单元格,以及是否需要包含列标题和 DataFrame 索引。如何处理特殊值(如 np.nannp.inf )。

1.指定工作表和单元格

sheet_name :指定将 DataFrame 写入的工作表名称。若不存在, pandas 会创建一个新的工作表。

 sheet_name="MySheet",   # 写入的工作表名称

startrowstartcol :指定从哪个行和列开始写入数据。在工作表中指定一个特定的位置来放置数据。

startrow=2,             # 从第三行开始写入(索引从0开始)
startcol=1,             # 从第二列开始写入(索引从0开始)

2.是否包含列标题和索引

header :布尔值,指定是否写入列标题。默认是 True

index :布尔值,指定是否写入行索引。默认是 True

header=True,            # 包含列标题
index=False,            # 不包含行索引

3.处理特殊值

na_rep :指定如何将 NaN 值表示在 Excel 中。默认是空字符串 ""

inf_rep :指定如何将正无穷大( np.inf )和负无穷大( -np.inf )表示在 Excel 中。默认是 "inf""-inf"

na_rep="NA",            # 将 NaN 表示为 "NA"
inf_rep="Infinity"      # 将 inf 和 -inf 表示为 "Infinity"

4.示例代码1

import pandas as pd
import numpy as np
import datetime as dt

data=[[dt.datetime(2020,1,1, 10, 13), 2.222, 1, True],
[dt.datetime(2020,1,2), np.nan, 2, False],
[dt.datetime(2020,1,2), np.inf, 3, True]]

df = pd.DataFrame(data=data,
columns=["Dates", "Floats", "Integers", "Booleans"])

df.index.name="index"
print(df)

df.to_excel("written_with_pandas.xlsx", 
sheet_name="Output",
startrow=1, 
startcol=1, 
index=True, 
header=True,
na_rep="<NA>", 
inf_rep="<INF>")

https://i-blog.csdnimg.cn/direct/fb5f9302da224693b50c0886472ec4f8.png

https://i-blog.csdnimg.cn/direct/6c05fba46d864fd2bdd8521ce7ed99eb.png

1.导入库

import datetime as dt

datetime :用于处理日期和时间的库。

2.创建数据

data = [
    [dt.datetime(2020, 1, 1, 10, 13), 2.222, 1, True],
    [dt.datetime(2020, 1, 2), np.nan, 2, False],
    [dt.datetime(2020, 1, 2), np.inf, 3, True]
]

data 是一个列表,其中每个子列表代表 DataFrame 的一行。

每一行包含四个值:一个日期时间对象、一个浮点数、一个整数和一个布尔值。

第二行包含一个 NaN 值( np.nan ),表示缺失数据。

第三行包含一个正无穷大值( np.inf )。

https://i-blog.csdnimg.cn/direct/3a55b9bb8e6a4090874aea2133860f50.png

3.创建 DataFrame

df = pd.DataFrame(data=data, 
columns=["Dates", "Floats", "Integers", "Booleans"])

df.index.name = "index"

https://i-blog.csdnimg.cn/direct/e892d5de599f408481c60777775c73e7.png

4.写入 Excel 文件

df.to_excel(
    "written_with_pandas.xlsx",
    sheet_name="Output",
    startrow=1,
    startcol=1,
    index=True,
    header=True,
    na_rep="<NA>",
    inf_rep="<INF>"
)

to_excel 方法用于将 DataFrame 写入 Excel 文件。

"written_with_pandas.xlsx" :输出的 Excel 文件名。

sheet_name="Output" :将数据写入名为 "Output" 的工作表。

startrow=1startcol=1 :数据将从 Excel 文件的第二行和第二列开始写入(索引从 0 开始)。

index=True :包括 DataFrame 的索引。

header=True :包括列标题。

na_rep="<NA>" :将 NaN 值替换为 "<NA>"

inf_rep="<INF>" :将 np.inf-np.inf 替换为 "<INF>"

5.示例代码2

用 with

import pandas as pd
import numpy as np

# 创建一个示例 DataFrame
data = {
    'A': [1, 2, np.nan, 4],
    'B': [np.inf, 5, 6, -np.inf],
    'C': [7, 8, 9, 10]
}
df = pd.DataFrame(data)

# 将 DataFrame 写入 Excel 文件
with pd.ExcelWriter("output.xlsx") as writer:
    df.to_excel(
        writer,
        sheet_name="MySheet",   # 写入的工作表名称
        startrow=2,             # 从第三行开始写入(索引从0开始)
        startcol=1,             # 从第二列开始写入(索引从0开始)
        header=True,            # 包含列标题
        index=False,            # 不包含行索引
        na_rep="NA",            # 将 NaN 表示为 "NA"
        inf_rep="Infinity"      # 将 inf 和 -inf 表示为 "Infinity"
    )


二 to_excel 方法和 ExcelClass 类

可以将多个 DataFrame 写入同一张或多张工作表。

分 3 次将同一个 DataFrame 写入工作表,前两次写入了工作表 1 的两个位置,第三次写入了工作表 2:

https://i-blog.csdnimg.cn/direct/efd3d62b39884c52b72fbeb7f36613eb.png

将 ExcelClass 用作了上下文管理器,因此当文件离开上下文管理器时(也就是离开由缩进定义的代码块时)会被自动写入磁盘。如果不像这样写的话,则必须显式地调用 writer.save() 。