python - 熊猫隐藏一列,留在df中,但不显示在html表中
问题描述
我有 +-300 行代码给我一个特定的 df 表。这个表需要以 html 显示。一切都已设置并完美运行。唯一的问题是,我在 df 中有一个列(这对于其他大型计算至关重要),我无法删除或调整。我想将此列保留在 df 中,但想在查看 html 表时隐藏它
例如(简化):
'''The table I have as df (cannot be changed fundamentally) '''
col1 col2 col3 col4
r1 2 34 45 23
r2 2 65 34 56
r3 2 34 34 54
r4 2 76 54 34
'''The Table I need to be displayed in html (without actually removing col1, just hiding it)'''
col2 col3 col4
r1 34 45 23
r2 65 34 56
r3 34 34 54
r4 76 54 34
解决方案
您可以创建自定义 CSS 样式。以下是添加的边框和隐藏列col0
:Styler.set_table_styles
css = [
{
'props': [
('border-collapse', 'collapse')]
},
{
'selector': 'th',
'props': [
('border-color', 'black'),
('border-style ', 'solid'),
('border-width','1px')]
},
{
'selector': 'td',
'props': [
('border-color', 'black'),
('border-style ', 'solid'),
('border-width','1px')]
},
{'selector': '.col0',
'props': [('display', 'none')]}]
html = df.style.set_table_styles(css).render()
编辑:
如果想要在没有 then 的情况下打印 DataFramecol1
可以使用DataFrame.drop
此列或仅选择列进行打印:
df_print = df.drop('col1', axis=1)
df_print = df[['col2', 'col3', 'col4']]