首页 > 解决方案 > Python Pandas:样式列标题

问题描述

我正在使用pandas 样式器根据列标题的名称为某些列提供背景颜色。虽然这按预期工作,但列标题的背景颜色不会改变。

这是我的脚本中应用您的样式的部分:

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)

有没有办法将style.apply() 函数不仅应用于列标题下方的单元格,还应用于包括列标题在内的整个列?

编辑:为澄清起见,这里是 excel 输出的 屏幕截图: excel 输出的屏幕截图

“标题 2”应具有与其下方单元格相同的背景颜色。

标签: pythonpandaspandas-styles

解决方案


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

使用大部分代码作为设置:

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')]}])

输出:

在此处输入图像描述

注意:我使用的是 Python 3.6+ 功能的 f-string。


推荐阅读