【问题标题】:Changing width of particular column in Dataframe更改数据框中特定列的宽度
【发布时间】:2021-08-14 11:40:24
【问题描述】:

我有 10-11 列的熊猫数据框。我想使用 pd.to_html(index=False,border=0) 将此数据框转换为 html。但是,我想更改返回表的 CSS。 我们可以更改数据框本身的列宽,或者从 pd.to_html() 中更改返回表的格式标签

预期表格的 HTML 代码

<table>
    <thead>
        <th width="5%">A</th>
        <th>B</th>
        <th>C</th>
        <th width="3%">D</th>
        <th>E</th>
        <th>F</th>
   </thead>
   <tbody>
   </tbody>
</table>

目前在 pd.to_html() 之后,我得到了这张表

<table border="0" class="dataframe">
    <thead>
        <tr style="text-align: right;">
           <th>A</th>
           <th>B</th>
           <th>C</th>
           <th>D</th>
           <th>E</th>
           <th>F</th>
        </tr>
   </thead>
   <tbody>
   </tbody>
</table>

如果 tr 标记将在 thead 标记之后从输出中删除,那就太好了,因为它不是必需的

【问题讨论】:

    标签: html css pandas dataframe


    【解决方案1】:

    你可以使用df的样式器:

    df_html = df.style.set_table_styles({
        'A': [{'selector': 'thead tr',
               'props': [('width', '5%')]}],
        'D': [{'selector': 'thead tr',
               'props': [('width', '3%')]}],
    })
    
    print(df_html.render(sparse_index=True))
    

    输出非常详细:

    <style type="text/css">
    #T_0167d_ thead tr.col0 {
      width: 5%;
    }
    #T_0167d_ thead tr.col3 {
      width: 3%;
    }
    </style>
    <table id="T_0167d_">
      <thead>
        <tr>
          <th class="blank level0" >&nbsp;</th>
          <th class="col_heading level0 col0" >A</th>
          <th class="col_heading level0 col1" >B</th>
          <th class="col_heading level0 col2" >C</th>
          <th class="col_heading level0 col3" >D</th>
          <th class="col_heading level0 col4" >E</th>
          <th class="col_heading level0 col5" >F</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多