使用 style.apply 时隐藏 Pandas 列

Hide a Pandas Column while using style.apply

我正在使用 df.style.applymap 渲染 pandas 数据框。我选择了样式而不是 to_html,因为我需要根据某些列值应用 css。挑战在于我想从显示中排除其中一列。因此,使用以下代码:

html = df.style.applymap(color_cell, subset=['columnName']).render()
with open('output.html', 'w') as f:
    f.write(html)

有什么方法可以 exclude/hide 我需要的列来设置其他列的样式吗?

您可以在呈现时删除要隐藏的列 HTML:

cols_2_hide = ['col1','col2']
df.drop(cols_2_hide, axis=1).style.applymap(color_cell, subset=['columnName']).render()

如果您需要函数 color_cell 中隐藏的列,您可以使用样式器的 hide_columns 功能。

df.style.hide_columns([hide_cols_list]).applymap(color_cell, subset=['columnname' + hide_cols_list]).render()