英文:
How can I style Pandas multiindex dataframe columns using threshold conditioning?
问题
我有一个如下的多级索引数据框。
我想要突出显示所有"diff"列,对于负数/正数值,使用不同的背景颜色。
例如,类似于以下方式:
if '- ' in diff.value:
'background-color: lightgreen'
else:
'background-color: pink'
我该如何编写一个样式化器(styler)?
我在 https://stackoverflow.com/questions/62850436/pandas-multiindex-style-highlight-a-row 看到了另一个类似的问题,但是我的数据框似乎不能像该线程中建议的那样进行分组。
此外,该线程中的方法不包含阈值条件。
英文:
I got one multiindex dataframe as below.
I would like to highlight all the "diff" columns, with different background colors on negative/positive values.
e.g. something like
if '-' in diff.value:
'background-color: lightgreen'
else:
'background-color: pink'
How do I write a styler for it?
I see another similar issue in https://stackoverflow.com/questions/62850436/pandas-multiindex-style-highlight-a-row
But my dataframe seems not able to groupby as the recommendation in that thread.
Also the method in that thread does not contain threshold conditioning
答案1
得分: 0
你可以使用子集来突出显示包含“-”的行。
def highlight_minus(row):
return np.where(row.astype(str).str.contains('-'),
'background-color: lightgreen',
'background-color: pink')
idx = pd.IndexSlice
slice_ = idx[:, idx[:, 'diff']]
s = df.style.apply(highlight_minus, axis=1, subset=slice_)
s.to_html('76374687.html')
英文:
You can use subset to highlight the row which contains -
def highlight_minus(row):
return np.where(row.astype(str).str.contains('-'),
'background-color: lightgreen',
'background-color: pink')
idx = pd.IndexSlice
slice_ = idx[:, idx[:,'diff']]
s = df.style.apply(highlight_minus, axis=1, subset=slice_)
s.to_html('76374687.html')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论