[英]How to exclude the total row (margins) from styling (subset) in a pandas pivot table
I have a .pivot_table with margins = True.我有一个边距 = True 的 .pivot_table。
I want to run .style.bar and .style.background_gradient on it but the problem is that margins (column totals) are also formatted and set to the maximum value so it looks non-descriptive.我想在其上运行 .style.bar 和 .style.background_gradient 但问题是边距(列总数)也被格式化并设置为最大值,因此它看起来不具有描述性。
I had a few ideas on how to solve this, however, none are working so far:我对如何解决这个问题有一些想法,但是,到目前为止还没有任何想法:
Here is the code:这是代码:
import pandas as pd
import numpy as np
import seaborn as sns
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7]})
df = df.pivot_table(values='D', index=['A','B'], columns=['C'], aggfunc=np.sum, margins=True, fill_value = 0)
df = (df.style.background_gradient(subset = 'large', cmap = sns.light_palette('red', as_cmap = True))
.background_gradient(subset = 'small', cmap = sns.light_palette('green', as_cmap = True)))
df
So the goal is to exclude the last row from formatting (All / Margins / Total column).所以目标是从格式中排除最后一行(全部/边距/总计列)。
You have to be a bit more explicit, but you can accomplish what you need with get_level_values
and a pd.IndexSlice
您必须更加明确,但是您可以使用
get_level_values
和pd.IndexSlice
完成您需要的pd.IndexSlice
u = df.index.get_level_values(0)
(df.style.background_gradient(
subset = pd.IndexSlice[u[:-1], 'large'],
cmap = sns.light_palette('red', as_cmap = True))
.background_gradient(
subset = pd.IndexSlice[u[:-1], 'small'],
cmap = sns.light_palette('green', as_cmap = True)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.