本文转发自文字及其回复内容: 根据多种条件设置pandas数据框中单元格的颜色格式
本文内容暂未测试,仅做记录。后续测试完再修改
我试图在数据帧中格式化特定列的单元格颜色,但无法根据多种条件进行设置。
这是我的数据帧(df):
Name ID Cel Date
0 Diego b000000005 7878 2565-05-31 20:53:00
1 Luis b000000015 6464 2017-05-11 20:53:00
2 Vidal b000000002 1100 2017-05-08 20:53:00
3 John b000000011 4545 2017-06-06 20:53:00
4 Yusef b000000013 1717 2017-06-06 20:53:00
我希望“日期”列中的值根据以下条件更改颜色:
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'])