简体   繁体   English

Python/Pandas 样式的列标题

[英]Python/Pandas style column headers

I would like to highlight specific column headers before exporting my dataframe to excel.在将数据框导出到 excel 之前,我想突出显示特定的列标题。

I have tried using the Pandas Styler to highlight specified columns.我曾尝试使用 Pandas Styler 来突出显示指定的列。

cm = sns.light_palette("green", as_cmap = True)

etc = etc.style.background_gradient(cmap=cm)

I started with this basic code to highlight my entire dataframe in hopes of adjusting and refining my selection.我从这个基本代码开始,以突出显示我的整个数据框,希望能调整和完善我的选择。 However, even using this broad approach not all values are highlighted.然而,即使使用这种广泛的方法,也不是所有的价值都被突出显示。 The desired result is highlighting just the column headers, if it is not possible then just the data associated to the specific header.所需的结果是仅突出显示列标题,如果不可能,则仅突出显示与特定标题相关联的数据。

Here's an answer based on the documentation for xlsxwriter :这是基于xlsxwriter文档的xlsxwriter

Start by creating an xlsxwriter object and writing the dataframe to it.首先创建一个xlsxwriter对象并将数据帧写入其中。 header=False means that we don't write the column names and startrow=1 leaves a blank row at the top (where we can put our custom columns next). header=False意味着我们不写列名并且startrow=1在顶部留下一个空白行(我们可以在下面放置自定义列)。 Then we get the relevant objects for the workbook and worksheet .然后我们得到workbookworksheet的相关对象。

writer = pd.ExcelWriter("output.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

We create a header format:我们创建一个标题格式:

header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})

Let's say you have three columns, A , B , and C , but only want to highlight A and C .假设您有三列ABC ,但只想突出显示AC We make a list of the column names we want to highlight and apply the formatting to them selectively:我们列出要突出显示的列名称,并有选择地对其应用格式:

columns_to_highlight = ['A', 'C']
for col_num, col_name in enumerate(df.columns.values):
    if col_name in columns_to_highlight:
        worksheet.write(0, col_num + 1, col_name, header_format)
    else:
        worksheet.write(0, col_num + 1, col_name)
writer.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM