突出显示列表中包含的熊猫数据框单元格

时间:2021-03-02 16:41:45

标签: python html pandas dataframe styles

我想突出显示包含在特定列表中的数据框单元格,以获得更好的性能,我希望这只发生在特定列上。

  1. 我知道我们应该设置 df.style background-color: yellow 属性 https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
  2. 我们应该使用 df.apply 而不是 df.applymap,后者是 element-wise 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)

1 个答案:

答案 0 :(得分:0)

经过数小时调查后问题解决,希望这可以帮助其他人。

df = pd.DataFrame([['Allen', 'red', 20], ['Tom', 'yellow', 30], ['Jack', 'blue', 40], ['Bob', 'grey', 50]],
columns=['name', 'color', 'age'])
df_result = df.style.apply(highlight_hot_color, subset=['color'])

with open('test.html','w') as f:
f.write(df_result.render())