python - 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”应具有与其下方单元格相同的背景颜色。
解决方案
好的,我想我想出了一种方法来处理使用 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。
推荐阅读
- sed - sed:仅在包含单词 z 的行上将所有出现的单词 X 替换为 Y
- javascript - 如果我们在网页上有多个表单,action 属性的值应该是多少?
- junit5 - 如何使用 assertThrows
- html - 这在 chrome 开发者工具中意味着什么
- axlsx - caxlsx / axlsx 数据透视表忽略空白并删除总计
- javascript - 是否有 openweathermap 的完整 JSON 响应的示例?
- python - 在 google ortools 中添加析取约束
- geth - GETH 如何达到 TX 的最大广播速度
- css - 使用 Angular 重新触发 css 动画
- r - 安装 xfun 的问题(对于 rmarkdown)