Example: Pandas Excel output with column formatting pandas 对excel 列做格式处理
An example of converting a Pandas dataframe to an Excel file with column formats using Pandas and XlsxWriter.
It isn’t possible to format any cells that already have a format such as the index or headers or any cells that contain dates or datetimes.
Note: This feature requires Pandas >= 0.16.

##############################################################################
#
# An example of converting a Pandas dataframe to an xlsx file
# with column formats using Pandas and XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2023, John McNamara, jmcnamara@cpan.org
#
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame(
{
"Numbers": [1010, 2020, 3030, 2020, 1515, 3030, 4545],
"Percentage": [0.1, 0.2, 0.33, 0.25, 0.5, 0.75, 0.45],
}
)
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_column_formats.xlsx", engine="xlsxwriter")
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name="Sheet1")
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets["Sheet1"]
# Add some cell formats.
format1 = workbook.add_format({"num_format": "#,##0.00"})
format2 = workbook.add_format({"num_format": "0%"})
# Note: It isn't possible to format any cells that already have a format such
# as the index or headers or any cells that contain dates or datetimes.
# Set the column width and format.
worksheet.set_column(1, 1, 18, format1)
# Set the format but not the column width.
worksheet.set_column(2, 2, None, format2)
# Close the Pandas Excel writer and output the Excel file.
writer.close()
分类:
pandas数据分析
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2021-10-20 如何通过云效Flow完成自动化部署—主机部署
2018-10-20 MySQL5.7.18基于GTID的主从复制过程实现
2017-10-20 一个客户端一键安装环境和服务的shell脚本