4

我试图用一个粗体列返回 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()]

但这似乎不起作用。有谁知道一个实用的解决方案?

4

3 回答 3

6

您可以使用df.style.set_propertiesand then.render()它将在正常表输出前.to_html()加上适当的style元素。(请注意,这不会将您的文本元素物理包装在 a<b><strong>您希望的任何标签内,而是纯粹为这些单元格提供样式 - 根据用例,这可能是您想要的,也可能不是您想要的)

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

(在 jupyter 笔记本中显示的示例)

在此处输入图像描述

于 2018-08-31T07:46:04.623 回答
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)
于 2018-08-31T07:31:04.840 回答
0

这是我的错,我没有正确解决问题,我需要在函数末尾有 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>')]
于 2018-08-31T08:03:10.753 回答