【发布时间】:2021-06-01 05:45:55
【问题描述】:
我想突出显示特定列表中包含的数据框单元格,以获得更好的性能,我希望这只发生在特定列上。
- 我知道我们应该设置
df.stylebackground-color: yellow属性 https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html - 我们应该使用
df.apply而不是df.applymap,后一种是元素方面的 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html#pandas.DataFrame.apply
示例代码清理如下,但根本不生成突出显示的项目。 谁能帮帮我,谢谢。
import pandas as pd
import os
import webbrowser
def write_data_to_file(filename, content):
file = open(filename, mode='w')
file.write(content)
file.close()
def highlight_hot_color(col):
hot_color = ['red', 'yellow', 'orange']
check = [item in hot_color for item in col]
return ['background-color: yellow' if v else '' for v in check]
if __name__ == '__main__':
df = pd.DataFrame([['Allen', 'red', 20], ['Tom', 'yellow', 30], ['Jack', 'blue', 40], ['Bob', 'grey', 50]],
columns=['name', 'color', 'age'])
df.style.apply(highlight_hot_color, subset=['color'])
html = df.to_html(index=False)
file_name = 'test.html'
path_name = os.path.abspath(file_name)
url = 'file://' + path_name
write_data_to_file(path_name, html)
webbrowser.open(url)
【问题讨论】:
标签: python html pandas dataframe styles