我的数据框如下所示:
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是星期。我试图有条件地给最后一列的行上色,以描述每周购买的物品的变化。我在这里使用了another answer的改编来实现这一点,但我遇到了IndexingError: Too many indexers
错误
下面是我修改过的代码:
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.apply(highlight3, axis=None)
将其应用于我的df
这里有一个解决方案:
结果是:
相关问题 更多 >
编程相关推荐