Python Pandas:样式列标题 [英] Python Pandas: Style column header

查看:645
本文介绍了Python Pandas:样式列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

I am using pandas styler to give some columns a background color, based on the name of the column header. 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?

为了澄清起见,这是excel输出的屏幕截图: Excel输出的屏幕截图

For clarification here is a screenshot of the excel output: screenshot of excel output

标题2"的背景颜色应与其下方的单元格相同.

"Header 2" should have the same background color as the cells below it.

推荐答案

好的,我想我想出了一种使用html'selectors'处理列标题格式的方法:

Okay, I think I figured out a way to handle formatting a column header using 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')]}])

输出:

注意:我正在使用f-string,这是Python 3.6+的一项功能.

这篇关于Python Pandas:样式列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆