如何从pandas pivot选项卡的样式设置(子集)中排除总行(边距)

2024-04-25 08:52:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.pivot_表,边距=True。在

我想跑。样式栏还有。style.background_渐变色但问题是,页边距(列总计)也被格式化并设置为最大值,因此它看起来不是描述性的。在

关于如何解决这个问题,我有一些想法,但是,到目前为止,没有一个是有效的:

  1. 尝试使用subset从.style中排除最后一行(页边距/总计列),但失败。在
  2. 将最后一行保存在单独的数据框中。从原始数据帧中删除最后一行,应用.style,然后连接两个数据帧,但是,这里我得到一个错误,我不能连接样式化的数据帧。在

代码如下:

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

Output

所以我们的目标是从格式化中排除最后一行(All/Margins/Total column)。在


Tags: 数据importtruedffoostyleasbar
1条回答
网友
1楼 · 发布于 2024-04-25 08:52:20

您必须更加明确一些,但是您可以使用get_level_valuespd.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)))

enter image description here

相关问题 更多 >