Python 自定义数据帧样式
显示了一个示例,介绍了如何根据值更改元素的字体颜色,该值可以正常工作:Python 自定义数据帧样式,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,显示了一个示例,介绍了如何根据值更改元素的字体颜色,该值可以正常工作: 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'
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)
def color\u negative\u red(val):
"""
获取标量并返回带有
css属性“color:red”表示负片
字符串,否则为黑色。
"""
颜色=‘红色’,如果val<0,则为‘黑色’
返回“颜色:%s”%color
s=df.style.applymap(彩色\负片\红色)
我的问题是如何实现一个函数,在整行应用字体颜色更改?您使用的是
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)
您可以添加一个示例数据集吗?