Format the color of a cell in a pandas dataframe according to multiple conditions

前端 未结 2 1689
攒了一身酷
攒了一身酷 2020-12-03 16:18

I am trying to format the color of a cell of an specific column in a data frame, but I can\'t manage to do it according to multiple conditions.

This is my dataframe

相关标签:
2条回答
  • 2020-12-03 17:01

    Use applymap:

    from datetime import datetime, timedelta
    import pandas as pd
    
    name = ['Diego', 'Luis', 'Vidal', 'John', 'Yusef']
    id = ['b000000005', 'b000000015', 'b000000002', 'b000000011', 'b000000013']
    cel = [7878, 6464, 1100, 4545, 1717]
    date = pd.to_datetime(['2017-05-31 20:53:00', '2017-05-11 20:53:00', '2017-05-08 20:53:00', 
                           '2017-06-06 20:53:00', '2017-06-06 20:53:00'])
    
    df = pd.DataFrame({'Name':name,'ID':id,'Cel':cel,'Date':date})
    
    def color(val):
        if val < datetime.now():
            color = 'green'
        elif val > datetime.now():
            color = 'yellow'
        elif val > (datetime.now() + timedelta(days=60)):
            color = 'red'
        return 'background-color: %s' % color
    
    df.style.applymap(color, subset=['Date'])
    

    Screenshot from Jupyter notebook. If you print the output instead, you'll just get a reference to the Styler object:

    print(df.style.applymap(color, subset=['Date']))
    <pandas.formats.style.Styler object at 0x116db43d0>
    
    0 讨论(0)
  • 2020-12-03 17:25

    The way it is written, no cells would be painted red. You should change the order, letting the condition to paint red before the one to paint yellow.

    0 讨论(0)
提交回复
热议问题