我有df1和df2。我想使用df2中的值在df1单元格中显示条形图。我可以使用下面的代码来应用其他形式的样式,但是对于酒吧,您不能使用此方法。
def color_cells(s):
if s > 90:
return 'color:{0}; font-weight:bold'.format('green')
elif s>80:
return 'background-color: light yellow;color:{0}; font-weight:regular'.format('dark yellow')
else:
return 'color:{0}; font-weight:bold'.format('red')
df1.style.apply(lambda x: df2.applymap(color_cells), axis=None)
我在df2中获取小节的代码是
df2.style.bar(color=['#d65f5f', '#5fba7d'])
如何将以上代码应用于df1?索引名和列名相同。
添加示例数据框:
df1=pd.DataFrame(np.random.rand(15, 10))
df2=pd.DataFrame(np.random.rand(15, 10)*100)
答案 0 :(得分:2)
这是执行此操作的代码:
df1=pd.DataFrame(np.random.rand(15, 10))
df2=pd.DataFrame(np.random.rand(15, 10)*100)
pct = (df2 - df2.min()) / (df2.max() - df2.min() )*100
def make_bar_style(x):
return f"background: linear-gradient(90deg,#5fba7d {x}%, transparent {x}%); width: 10em"
pct.applymap(make_bar_style).shape
df1.style.apply(lambda x: pct.applymap(make_bar_style), axis=None)
结果是:
要说明条尺寸是由df2驱动的事实,请考虑以下内容:
df2 = pd.DataFrame(np.mgrid[0:15, 0:10][0])
结果为: