如何通过比较两列来为pandas表着色

时间:2017-06-27 20:53:08

标签: python pandas styles

例如,我有一个包含两列A和B的数据帧。如果A> B,我想把红色排成一排;如果A< = B,我想将该行着色为绿色。知道我该怎么办?谢谢!

1 个答案:

答案 0 :(得分:9)

来自docs

def highlight_greater(row):

    if row['A'] > row['B']:
        color = 'red'
    elif row['A'] <= row['B']:
        color = 'green'

    background = ['background-color: {}'.format(color) for _ in row]

    return background

df.style.apply(highlight_greater, axis=1)