简体   繁体   English

Python Pandas:样式列标题

[英]Python Pandas: Style column header

I am using pandas styler to give some columns a background color, based on the name of the column header.我正在使用pandas 样式器根据列标题的名称为某些列提供背景颜色。 While this works as intended, the background color of the column header doesn't change.虽然这按预期工作,但列标题的背景颜色不会改变。

Here is the part in my script where thy style is applied:这是我的脚本中应用您的样式的部分:

def highlight_col(x):
    if x.name in added_columns:
        return ['background-color: #67c5a4']*x.shape[0]
    elif x.name in dropped_columns:
        return ['background-color: #ff9090']*x.shape[0]
    else:
        return ['background-color: None']*x.shape[0]



old = old.style.apply(highlight_col, axis=0)

Is there a way to apply the style.apply()-function not only to the cells below the column header, but the complete column including the column header?有没有办法将style.apply() 函数不仅应用于列标题下方的单元格,还应用于包括列标题在内的整个列?

Edit: For clarification here is a screenshot of the excel output: screenshot of excel output编辑:为澄清起见,这里是 excel 输出的屏幕截图: excel 输出的屏幕截图

"Header 2" should have the same background color as the cells below it. “标题 2”应具有与其下方单元格相同的背景颜色。

Okay, I think I figured out a way to handle formatting a column header using html 'selectors':好的,我想我想出了一种方法来处理使用 html 'selectors' 格式化列标题:

Using much of your code as setup:使用大部分代码作为设置:

df = pd.DataFrame('some value', columns=['Header1','Header2','Header3'], index=np.arange(12))
added_columns = 'Header2'
dropped_columns = 'Header1'

def highlight_col(x):
    if x.name in added_columns:
        return ['background-color: #67c5a4']*x.shape[0]
    elif x.name in dropped_columns:
        return ['background-color: #ff9090']*x.shape[0]
    else:
        return ['background-color: None']*x.shape[0]


col_loc_add = df.columns.get_loc(added_columns) + 2
col_loc_drop = df.columns.get_loc(dropped_columns) + 2

df.style.apply(highlight_col, axis=0)\
  .set_table_styles(
     [{'selector': f'th:nth-child({col_loc_add})',
       'props': [('background-color', '#67c5a4')]},
     {'selector': f'th:nth-child({col_loc_drop})',
       'props': [('background-color', '#ff9090')]}])

Output:输出:

在此处输入图像描述

Note: I am using f-string which is a Python 3.6+ feature.注意:我使用的是 Python 3.6+ 功能的 f-string。

You can use np.vstack() to stack the column names like below and create a fresh dataframe to apply the function, then export to excel with header=False :您可以使用np.vstack()来堆叠列名,如下所示,并创建一个新的数据框来应用该函数,然后使用header=False导出到 excel:

Using @Scott's data and piR's function, Setup:使用@Scott 的数据和 piR 的函数,设置:

df = pd.DataFrame('some value', columns=['Header1','Header2','Header3'], index=np.arange(12))
def f(dat, c='red'):
    return [f'background-color: {c}' for i in dat]

You can do:你可以做:

pd.DataFrame(np.vstack((df.columns,df.to_numpy())),columns=df.columns).style.apply(
                  f,subset=['Header2']).to_excel('file.xlsx',header=False,index=False)

Output of excel file: excel文件的输出: 在此处输入图像描述

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

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