python - 自定义样式 Pandas 数据框

标签 python python-3.x pandas dataframe

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/

相关文章:

python - 如何在 md5 指纹识别时跳过不可散列的(损坏的)文件?

python - Pandas Groupby : Is there normalization functionality? 或查找组中总比率的最佳方法

python - pandas 数据框切片的乘法

Python - 计算来自 txt 文件的标签的行之间的时间差

Python:细菌生长模型、嵌套 while 循环、逻辑错误

python - 如何在txt文件中插入随机空格?

Python返回类型注释

python - 将 @property 与另一个装饰器结合起来

python - PyUserInput - 停止 PyMouseEvent

python - pandas 将相同的值合并在同一行中