Pandas样式栏颜色取决于条件?

2024-09-30 00:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

如果列的style.bar.color属性是基于某种条件计算的,我如何呈现Pandas df?在

示例:

df.style.bar(subset=['before', 'after'], color='#ff781c', vmin=0.0, vmax=1.0)

enter image description here

我希望其中一列(df['before'])保持不变的颜色,另一列(df['after'])计算如下:

^{pr2}$

Tags: 示例pandasdf属性style颜色bar条件
1条回答
网友
1楼 · 发布于 2024-09-30 00:31:57

一种方法是使用pd.IndexSlicedf.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)

输出:

enter image description here

相关问题 更多 >

    热门问题