documentation显示了一个示例,说明如何根据值更改元素的字体颜色,它按预期工作正常:
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
s = df.style.applymap(color_negative_red)
我的问题是如何实现一个函数,而不是在整行中应用字体颜色更改?
最佳答案
您使用 DataFrame
,因此如果行中至少有一个值小于 0
,它将行设置为 red
:
def color_negative_red(x):
c1 = 'background-color: red'
c2 = 'background-color: black'
df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
df1 = df1.where((x > 0).all(axis=1), c1)
return df1
df.style.apply(color_negative_red, axis=None)
关于python - 自定义样式 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634751/