我有 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)
1 回答
慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
這是執行此操作的代碼:
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])
結果是:

添加回答
舉報
0/150
提交
取消
