python - 如何更改 pandas DataFrame header 的样式?

标签 python css pandas

我有以下生成 HTML 表格的 Python 脚本。现在我想更改表格的某些样式,但在更改标题的字体大小时遇到​​问题。

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 3, 4]})

html = (df.style
        .set_table_styles({'selector': 'th', 'props': [('font-size', '5pt')]})
        .set_properties(**{'font-size': '10pt'}).render())

f = open('test.html', 'wb')
f.write(html)

如何更改标题的样式?

<style  type="text/css" >
    #T_f85befdc_2093_11e8_85e2_08002718d81b  {
    }    #T_f85befdc_2093_11e8_85e2_08002718d81b  {
    }    #T_f85befdc_2093_11e8_85e2_08002718d81brow0_col0 {
            font-size:  10pt;
        }    #T_f85befdc_2093_11e8_85e2_08002718d81brow1_col0 {
            font-size:  10pt;
        }    #T_f85befdc_2093_11e8_85e2_08002718d81brow2_col0 {
            font-size:  10pt;
        }    #T_f85befdc_2093_11e8_85e2_08002718d81brow3_col0 {
            font-size:  10pt;
        }</style>  
<table id="T_f85befdc_2093_11e8_85e2_08002718d81b" > 
<thead>    <tr> 
        <th class="blank level0" ></th> 
        <th class="col_heading level0 col0" >col1</th> 
    </tr></thead> 
<tbody>    <tr> 
        <th id="T_f85befdc_2093_11e8_85e2_08002718d81b" class="row_heading level0 row0" >0</th> 
        <td id="T_f85befdc_2093_11e8_85e2_08002718d81brow0_col0" class="data row0 col0" >1</td> 
    </tr>    <tr> 
        <th id="T_f85befdc_2093_11e8_85e2_08002718d81b" class="row_heading level0 row1" >1</th> 
        <td id="T_f85befdc_2093_11e8_85e2_08002718d81brow1_col0" class="data row1 col0" >2</td> 
    </tr>    <tr> 
        <th id="T_f85befdc_2093_11e8_85e2_08002718d81b" class="row_heading level0 row2" >2</th> 
        <td id="T_f85befdc_2093_11e8_85e2_08002718d81brow2_col0" class="data row2 col0" >3</td> 
    </tr>    <tr> 
        <th id="T_f85befdc_2093_11e8_85e2_08002718d81b" class="row_heading level0 row3" >3</th> 
        <td id="T_f85befdc_2093_11e8_85e2_08002718d81brow3_col0" class="data row3 col0" >4</td> 
    </tr></tbody> 
</table> 

最佳答案

我发现我需要将一个参数作为列表传递给 Styler.set_table_styles()。它现在正在使用以下代码。

html = (df.style
        .set_table_styles([{'selector': 'th', 'props': [('font-size', '5pt')]}])
        .set_properties(**{'font-size': '10pt'}).render())

关于python - 如何更改 pandas DataFrame header 的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58936299/

相关文章:

css 错误溢出

python - 如何在一列上执行 pandas groupby 操作,但将另一列保留在生成的数据框中

python - 一种热编码 - 将多列编码为一列

python - 多线程工具

Python - 将单词分为 3 组

javascript - 如何将一组单选按钮居中对齐在测验标题的中心并保持响应?

html - 圆 Angular 在IE8中显示白边

python - 在Python中合并一个单一数据帧中的列

python - 如何在 Python Pandas 中使用循环更改数据帧?

python - 按小时值对列 'Time' 进行分组