下面是我正在使用的示例脚本。我试图同时将两个styler函数应用到一个 Dataframe ,但如您所见,它只调用colors2函数。同时应用两个函数的最佳方式是什么?
import pandas as pd
df = pd.DataFrame(data=[[-100,500,400,0,222,222], [9000,124,0,-147,54,-56],[77,0,110,211,0,222], [111,11,-600,33,0,22,],[213,-124,0,-147,54,-56]])
df.columns = pd.MultiIndex.from_product([['x','y','z'], list('ab')])
def colors(i):
if i > 0:
return 'background: red'
elif i < 0:
return 'background: green'
elif i == 0:
return 'background: yellow'
else:
''
def colors2(i):
if i < 0:
return 'background: red'
elif i > 0:
return 'background: green'
elif i == 0:
return 'background: yellow'
else:
''
idx = pd.IndexSlice
df.style.applymap (colors, subset=pd.IndexSlice[:, idx['x','b']])
df.style.applymap (colors2, subset=pd.IndexSlice[:, idx[:, 'b']])
1条答案
按热度按时间htrmnn0y1#
Chain your
applymap
commands in the desired order (last one prevails):Here
pd.IndexSlice['x','b']]
is more restrictive thanpd.IndexSlice[:, 'b']
so we use it last.Another option could be to use a single function and to decide the color based on the labels inside it.
Output: