PYTHON Pandas - 使用 Pandas 基于其他数据框中的值的数据框样式
PYTHON Pandas - Using Pandas Styling for dataframe based on values in other dataframe
我一直在处理这个挑战,但我想不出一个合适的解决方案。
我有两个形状相同的数据框。
我想做的是,根据数据框 2 中包含的值为数据框 1 着色。
我可以根据自己的值为 Dataframe 2 着色,但我无法将 'Styling' 传输到 Dataframe 1。
这是我的代码:
df1 = ...
df2 = ...
def apply_color(val):
colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}
return 'background-color: {}'.format(colors[val]) if val else ''
df2.style.applymap(df2)
谁能指导我完成这个? :-)
非常感谢!
此致,
毫克
使用applymap
with get
by dict for DataFrame
for colors and pass to Styler.apply
:
df1 = pd.DataFrame({
'B':[4,5,4],
'C':[7,8,9],
'D':[1,3,5],
})
df2 = pd.DataFrame({
'B':[1,np.nan,4],
'C':[np.nan,2,np.nan],
'D':[1,3,np.nan],
})
def apply_color(x):
colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}
return df2.applymap(lambda val: 'background-color: {}'.format(colors.get(val,'')))
df1.style.apply(apply_color, axis=None)
我一直在处理这个挑战,但我想不出一个合适的解决方案。
我有两个形状相同的数据框。
我想做的是,根据数据框 2 中包含的值为数据框 1 着色。
我可以根据自己的值为 Dataframe 2 着色,但我无法将 'Styling' 传输到 Dataframe 1。
这是我的代码:
df1 = ...
df2 = ...
def apply_color(val):
colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}
return 'background-color: {}'.format(colors[val]) if val else ''
df2.style.applymap(df2)
谁能指导我完成这个? :-)
非常感谢!
此致, 毫克
使用applymap
with get
by dict for DataFrame
for colors and pass to Styler.apply
:
df1 = pd.DataFrame({
'B':[4,5,4],
'C':[7,8,9],
'D':[1,3,5],
})
df2 = pd.DataFrame({
'B':[1,np.nan,4],
'C':[np.nan,2,np.nan],
'D':[1,3,np.nan],
})
def apply_color(x):
colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}
return df2.applymap(lambda val: 'background-color: {}'.format(colors.get(val,'')))
df1.style.apply(apply_color, axis=None)