本文介绍了pandas DataFrame中的粗体to_html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用一个粗体列返回df.to_html().我只尝试过
I am trying to return df.to_html() with one bold column. I have only tried
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()]
但是它似乎不起作用.有谁知道一种可行的解决方案?
But it doesn't seem to work. Does any one know a practical solution?
推荐答案
您忘了分配输出,但是更快的矢量化解决方案是将列转换为字符串,并使用f
字符串添加不带apply
的字符串:
You forget assign output, but faster vectorized solution is convert column to string and add strings with no apply
with f
strings:
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)
这篇关于pandas DataFrame中的粗体to_html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!