【问题标题】:Highlight pandas dataframe cells contained in a list突出显示列表中包含的 pandas 数据框单元格
【发布时间】:2021-06-01 05:45:55
【问题描述】:

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

  1. 我知道我们应该设置df.stylebackground-color: yellow属性 https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
  2. 我们应该使用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


    【解决方案1】:

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

    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())
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多