pandas系列之导出为.xlsx文件(二)

586 阅读2分钟

本文所用表格内容如下:

商品信息表

image-20210801112646658.png

用户购物表

image-20210801113021656.png

5.设置编码格式

修改编码格式可以通过encoding参数进行

goods_df = pd.read_excel(r'C:\Users\viruser.v-desktop\Desktop\商品信息表.xlsx')
goods_df.to_excel(excel_writer='test.xlsx', sheet_name='测试文件', index=False,columns=['分类', '名称'], encoding='utf-8')

6.缺失值处理

虽然数据预处理阶段已经有缺失值的处理了,但是数据分析过程中可能也会产生缺失值,所以导出时仍然需要处理缺失值。

goods_df = pd.read_excel(r'C:\Users\viruser.v-desktop\Desktop\商品信息表.xlsx')
goods_df.to_excel(excel_writer='test.xlsx', sheet_name='测试文件', index=False, columns=['分类', '名称'], encoding='utf-8',
                  na_rep=0)

result:

原始表格

image-20210802135718575.png

缺失值处理后:

image-20210802140234143.png

7.无穷值处理

无穷值(inf)与缺失值(NaN)都是异常数据,无穷值一般是通过除数为0的方式得到的。无穷值的存在会导致数值计算报错,所以计算前先对无穷值进行处理

7.1 无穷值的生成

7.1.1 正无穷值的生成

print(float('inf'))

result:

inf

7.1.2 负无穷值的生成

print(float('-inf'))

result:

-inf

7.2 无穷值替换填充

goods_df = pd.read_excel(r'C:\Users\viruser.v-desktop\Desktop\商品信息表.xlsx')
goods_df.to_excel(excel_writer='test.xlsx', sheet_name='测试文件', index=False, columns=['分类', '名称', "销量"], encoding='utf-8',
                  na_rep=0, inf_rep=0)

替换前:

image-20210802153453361.png

替换后:

image-20210802153522536.png

8.将文件导出到多个sheet

有的时候一个脚本一次会生成多个文件,可以将多个文件分别导出成多个文件,也可以将多个文件放在一个文件的不同Sheet中,这时要用到ExcelWriter()函数将多个文件分别导出到同一文件的不同Sheet中.具体示例如下:

import pandas as pd
​
goods_df = pd.read_excel(r'C:\Users\viruser.v-desktop\Desktop\商品信息表.xlsx')
user_df = pd.read_excel(r'C:\Users\viruser.v-desktop\Desktop\用户购物表.xlsx')
writer = pd.ExcelWriter('many.xlsx', engine='xlsxwriter')
goods_df.to_excel(writer, sheet_name='商品')
user_df.to_excel(writer, sheet_name='用户')
writer.save()

result:

image-20210802162123049.png

image-20210802162149488.png

注:这里要安装xlsxwriter模块

通过 pip install xlsxwriter的方式进行安装即可