简体   繁体   English

如何从熊猫数据透视表中的样式(子集)中排除总行(边距)

[英]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:我对如何解决这个问题有一些想法,但是,到目前为止还没有任何想法:

  1. Tried somehow excluding last row (the margins / total columns) from .style using subset, but failed.尝试以某种方式使用子集从 .style 中排除最后一行(边距/总列),但失败了。
  2. Saving the last row in a separate data frame.将最后一行保存在单独的数据框中。 Removing the last row from the original data frame, applying .style and then concatenating both data frames, however, here I get an error that I cannot concatenate styled data frames.从原始数据框中删除最后一行,应用 .style 然后连接两个数据框,但是,在这里我得到一个错误,我无法连接样式数据框。

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_valuespd.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM