如何突出显示数据行? Python Pandas 问题

How Do I Highlight Rows Of Data? Python Pandas issue

我试图突出显示曲奇口味为巧克力的任何行。我该怎么做呢?我正在尝试使用 df.style,但运气不好...

import pandas as pd

Excel_file = "Cookies2.xlsx"

x = pd.read_excel(Excel_file)

sorted_by_Cookie_Boxes_Sold = x.sort_values(['Cookie_Boxes_Sold'], 
ascending=False)

df = pd.DataFrame(sorted_by_Cookie_Boxes_Sold)

df.style

首先尝试定义规则:

def color_chocolate_red(val):
    color = 'red' if val == 'chocolate' else 'black'
    return 'color: {}'.format(color)

然后应用它:

result = df.style.applymap(color_chocolate_red)

对于整行你可以使用这个:

def highlight_row(x):
    df = x.copy()
    mask = df['column'] == 'chocolate'
    df.loc[mask, :] = 'color: red'
    df.loc[~mask,:] = 'color: black'
    return df