问题
How can I render a Pandas df where one of the columns' style.bar.color
property is computed based on some condition?
Example:
df.style.bar(subset=['before', 'after'], color='#ff781c', vmin=0.0, vmax=1.0)
Instead of having both columns highlight with #ff781c
, I'd like one of the columns (df['before']
) to remain that same constant color, and the other column (df['after']
) to be computed as:
def compute_color(row):
if row['after'] >= row['before']:
return 'red'
else:
return 'green
回答1:
One way to do is to use pd.IndexSlice
to create subset for df.style.bar
:
i_pos = pd.IndexSlice[df.loc[(df['after']>df['before'])].index, 'after']
i_neg = pd.IndexSlice[df.loc[~(df['after']>df['before'])].index, 'after']
df.style.bar(subset=['before'], color='#ff781c', vmin=0.0, vmax=1.0)\
.bar(subset=i_pos, color='green', vmin=0.0, vmax=1.0)\
.bar(subset=i_neg, color='red', vmin=0.0, vmax=1.0)
Output:
来源:https://stackoverflow.com/questions/57580589/pandas-style-bar-color-based-on-condition