1

这是 excel 格式的 pandas 的输出:

Id      comments     number
1       so bad        1
1       so far        2
2       always        3
2       very good     4
3       very bad      5
3       very nice     6
3       so far        7
4       very far      8
4       very close    9
4       busy          10

Id column我想使用 pandas 为它们的值为偶数的行赋予颜色(例如:灰色) 。例如,第 3 行和第 4 行有偶数Id,但第 5、6 和 7 行有奇数Id。有没有办法使用熊猫来做到这一点?

4

1 回答 1

1

正如文档http://pandas.pydata.org/pandas-docs/stable/style.html中所解释的,您基本上想要做的是编写一个样式函数并将apply其写入样式对象。

def _color_if_even(s):
    return ['background-color: grey' if val % 2 == 0 else '' for val in s]

并在我的 Styler 对象上调用它,即

df.style.apply(_color_if_even, subset=['id'])
于 2016-12-22T01:16:21.090 回答