【问题标题】:Bold column in pandas DataFrame to_htmlpandas DataFrame to_html中的粗体列
【发布时间】:2019-02-06 04:41:51
【问题描述】:

我试图用一个粗体列返回 df.to_html()。我只试过

df = pd.DataFrame({'important_column': [1,2,3,4], 
                   'dummy_column': [5,6,7,8]})

def some_function()
      df.apply(lambda x: '<b>' + str(df['important_column']) + '</b>', axis=1)
      return [df.to_html()]

但它似乎不起作用。有人知道实用的解决方案吗?

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    您可以使用df.style.set_properties,然后使用.render(),这将在.to_html() 的正常表输出前加上适当的style 元素。 (请注意,这不会将您的文本元素物理包装在 &lt;b&gt;&lt;strong&gt; 或您希望的任何标签中,而是纯粹为这些单元格提供样式 - 这可能是您想要的,也可能不是您想要的,具体取决于用例)

    html = df.style.set_properties(
        subset=['important_column'], 
        **{'font-weight': 'bold'}
    ).render()
    

    (jupyter notebook 中的示例)

    【讨论】:

      【解决方案2】:

      您忘记了分配输出,但更快的矢量化解决方案是将列转换为字符串并添加没有apply 的字符串和f 字符串:

      def some_function():
      
          df['important_column'] = [f'<b>{x}</b>' for x in df['important_column']]
          #alternative1 
          df['important_column'] =  '<b>' + df['important_column'].astype(str) + '</b>'
          #alternative2
          #df['important_column'] = df['important_column'].apply(lambda x: '<b>' + str(x) + '</b>')
          #alternative3, thanks @Jon Clements
          #df['important_column'] = df['important_column'].apply('<b>{}</b>?'.format)
          return df.to_html()
      

      编辑:

      df['important_column'] = [f'<b>{x}</b>' for x in df['important_column']]
      print (df.to_html(escape=False))
      <table border="1" class="dataframe">
        <thead>
          <tr style="text-align: right;">
            <th></th>
            <th>important_column</th>
            <th>dummy_column</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th>0</th>
            <td><b>1</b></td>
            <td>5</td>
          </tr>
          <tr>
            <th>1</th>
            <td><b>2</b></td>
            <td>6</td>
          </tr>
          <tr>
            <th>2</th>
            <td><b>3</b></td>
            <td>7</td>
          </tr>
          <tr>
            <th>3</th>
            <td><b>4</b></td>
            <td>8</td>
          </tr>
        </tbody>
      </table>
      

      时间安排

      df = pd.DataFrame({'important_column': [1,2,3,4], 
                         'dummy_column': [5,6,7,8]})
      
      df = pd.concat([df] * 10000, ignore_index=True)
      
      In [213]: %timeit df['important_column'] = [f'<b>{x}</b>' for x in df['important_column']]
      74 ms ± 22.2 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
      
      In [214]: %timeit df['important_column'] = df['important_column'].apply(lambda x: '<b>' + str(x) + '</b>')
      150 ms ± 7.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
      
      In [216]: %timeit df['important_column'].apply('<b>{}</b>?'.format)
      133 ms ± 238 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
      
      In [217]: %timeit '<b>' + df['important_column'].astype(str) + '</b>'
      266 ms ± 1.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
      

      【讨论】:

      • df['important_column'].apply('&lt;b&gt;{}&lt;/b&gt;?'.format) 也应该是相当高效的 - 它会让格式处理转换为字符串,它使标记更具可读性并且更容易调整恕我直言。
      • @JonClements - 你是对的,刚刚测试过。 df = pd.concat([df] * 1000, ignore_index=True) In [198]: %timeit df['important_column'].apply('&lt;b&gt;{}&lt;/b&gt;?'.format) In [199]: %timeit '&lt;b&gt;' + df['important_column'].astype(str) + '&lt;/b&gt;'
      • 1.75 ms ± 278 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 2.6 ms ± 24.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      【解决方案3】:

      我没有正确解决问题是我的错,我需要在函数末尾有 df.to_html(),因为这个 html 显示在网页上,是用烧瓶创建的,所以不是以上对我有用。

      我找到了一个便宜的解决方法,它适合我的需要:

      def some_function():
          df['important_column'] = '^' + df['important_column'].astype(str) + '+'
          return [df.to_html(classes='greenARTstyle').replace('^', '<b>').replace('+', '</b>')]
      

      【讨论】:

      • 检查我的编辑,需要print (df.to_html(escape=False))
      • 您的烧瓶中是否已经有了您正在使用的样式表?如果是这种情况,那么您似乎可以返回 df.to_html(classes='important_table') 以便识别它,然后将现有样式表调整为具有 table.important_table td.col1 { font-weight: bold }...
      • 感谢@jezrael 的作品!对 Jon 来说,我对 CSS 很陌生,而且我很挣扎。我们公司的网页设计师很少,我创建的网页仅用于内部需求,所以......是的,我不时需要最简单的解决方案
      • 那样——除非你真的,真的需要在你的单元格周围有&lt;b&gt;标签(如果它只是为了在应用程序中显示,可能不需要)——然后你只需让浏览器为按样式列...也意味着如果您想更改颜色/大小/对齐方式或背景 - 您可以在一个地方执行此操作而无需引入更多 html(并担心转义)...
      • @Finrod 很好......只是说这实际上不是一个简单的方法......在你的 jinja2 模板中使用 {{ table|safe }} 之类的东西并从我下面的答案中传递 html 也很惊讶table 到您的模板不起作用:(。
      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2020-05-09
      • 1970-01-01
      • 2021-03-11
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多