gpt4 book ai didi

python - 如何使用 xlsxwriter 格式化索引列?

转载 作者:行者123 更新时间:2023-11-28 19:11:14 25 4
gpt4 key购买 nike

我正在使用 xlsxwriterset_column 函数来格式化我的 excel 输出中的列。

但是,当应用于索引列(或多索引情况下的索引列)时,格式化似乎被忽略了。

我找到了一个解决方法,到目前为止是用 reset_index 引入一个假索引,然后将 index=False 传递给 to_excel 函数,然后是很好的合并功能多索引也将消失。

有什么想法吗?

import pandas as pd
import numpy as np

from Config import TEMP_XL_FILE

def temp():
' temp'
pdf = pd.DataFrame(np.random.randn(6,4), columns=list('ABCD'))
pdf.set_index('A', drop=True, inplace=True)
writer = pd.ExcelWriter(TEMP_XL_FILE, engine='xlsxwriter')
pdf.to_excel(writer, 'temp')
workbook = writer.book
worksheet = writer.sheets['temp']
tempformat = workbook.add_format({'num_format': '0%', 'align': 'center'})
worksheet.set_column(-1, 3, None, tempformat)
writer.save()

if __name__ == '__main__':
temp()

最佳答案

pandas ExcelWriter 覆盖索引列中的 XlsxWriter 格式。为防止这种情况,请将 pandas header_style 更改为 None

header_style = {"font": {"bold": True},
"borders": {"top": "thin",
"right": "thin",
"bottom": "thin",
"left": "thin"},
"alignment": {"horizontal": "center",
"vertical": "top"}}

这样做:

import pandas.io.formats.excel

pandas.io.formats.excel.header_style = None

另见

关于python - 如何使用 xlsxwriter 格式化索引列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com