我正试图绘制一张彩色的桌子,
此post提供了一种方法。
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'])
与该帖子完全相同的代码会产生不同的输出。
缺少边框,颜色也与帖子中的不同。
我想念什么?
答案 0 :(得分:1)
首先使用熊猫style
通过自定义功能设置背景颜色,然后使用Styler.set_table_styles
设置css
样式:
df = pd.DataFrame({'Red':[1,1,0,0,0],'Yellow':[0,0,1,0,1],'Green':[0,0,0,1,0]})
print (df)
def color(x):
c1 = 'background-color: green'
c2 = 'background-color: yellow'
c3 = 'background-color: red'
c4 = ''
m = x == 1
print (m)
df1 = pd.DataFrame(c4, index=x.index, columns=x.columns)
df1.loc[m['Red'], 'Red'] = c1
df1.loc[m['Yellow'], 'Yellow'] = c2
df1.loc[m['Green'], 'Green'] = c3
return df1
df.style.apply(color,axis=None).set_table_styles(
[{
'selector': 'th',
'props': [
('background-color', 'blue'),
('color', 'white'),
('border-color', 'black'),
('border-style ', 'solid'),
('border-width','1px')]
},
{
'selector': 'td',
'props': [
('border-color', 'black'),
('border-style ', 'solid'),
('border-width','1px')]
},
{'selector': '.row_heading',
'props': [('display', 'none')]},
{'selector': '.blank.level0',
'props': [('display', 'none')]}])
答案 1 :(得分:0)