Python 条件颜色列

Python 条件颜色列,python,pandas,pandas-apply,pandas-styles,Python,Pandas,Pandas Apply,Pandas Styles,我的数据框如下所示: Week Item Buyer 11 12 13 0 clothes buyerID1 2 3 4 1 food buyerID2 2 1 1 2 water buyerID 7 5 1 11、12、13是星期。我试图有条件地给最后一列的行上色,以描述每周购买的物品的变化。我使用了对here的修改来实现这一点,但我遇到了一个索引错误:索引器错误太多 下面是我修改过的

我的数据框如下所示:

Week    Item    Buyer   11  12  13  
0   clothes buyerID1    2   3   4   
1   food    buyerID2    2   1   1   
2   water   buyerID     7   5   1   
11、12、13是星期。我试图有条件地给最后一列的行上色,以描述每周购买的物品的变化。我使用了对here的修改来实现这一点,但我遇到了一个索引错误:索引器错误太多

下面是我修改过的代码:

def highlight3(x):
#if increase
c1 = 'background-color: green'

#if decrease
c2 = 'background-color: red'

c3 = ''

#last row greater than value in second to last row
m1 = x.iloc[:, -1] > x.iloc[:, -2]

#last row lesser than value in second to last row
m2 = x.iloc[:, -1] < x.iloc[:, -2]

out = np.select([m1, m2], [c1, c2], default=c3)
return pd.DataFrame(out, index=x.index, columns=x.columns)
然后我使用:df.applyhighlight3,axis=None将其应用于我的df

data = """Week    Item    Buyer   11  12  13  
0   clothes buyerID1    2   3   4   
1   food    buyerID2    2   1   1   
2   water   buyerID     7   5   1   """
df = pd.read_csv(StringIO(data), sep="\s+")

green = 'background-color: green'
red = 'background-color: red'

def style_last_week(x):
    s = pd.Series([""] * x.size)
    if x[-1] > x[-2]:
        s[x.size -1 ] = green

    if x[-2] > x[-1]:
        s[x.size -1 ] = red

    return s

df.style.apply(style_last_week, axis=1)
结果是:


这回答了你的问题吗?这给了我一个关键错误:1。不知道为什么-我正在复制粘贴您的代码我将x[-1]更改为x.iloc[-1],它可以工作,但它丢失了df具有的默认间隔和备用行的颜色-知道我如何保持吗@Roy2012I添加了创建数据帧的代码。你能试试吗?这是图像。我正在使用谷歌Colab——这有什么不同吗@Roy2012