Pandas透视表中是否有添加多列差异的功能?

2w3rbyxf  于 2023-01-11  发布在  其他
关注(0)|答案(1)|浏览(113)

我有以下PandasDataFrame:

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar",'foo' ],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two", 'two'],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large", 'large'],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7,8],
               })

输出如下:

print(df)

    A   B   C       D
0   foo one small   1
1   foo one large   2
2   foo one large   2
3   foo two small   3
4   foo two small   3
5   bar one large   4
6   bar one small   5
7   bar two small   6
8   bar two large   7
9   foo two large   8

那么我将按如下方式创建透视表:

table = pd.pivot_table(df, values='D', index=['A'],
                    columns=['B','C'])

输出如下:

print(table)

B   one             two
C   large   small   large   small
A               
bar   4      5       7        6
foo   2      1       8        3

如何将largesmall之间的差值(large-small)相加以得到onetwo(下表中的diff)?

B   one                 two
C   large   small diff  large   small difff
A               
bar   4        5   -1     7       6    1
foo   2        1    1     8       3    5

我看到了一些以前的答案,但只处理了1列。此外,理想情况下,将使用aggfunc完成
此外,如何将表格重新转换为初始格式?预期输出为:

A   B   C     D 
0  foo one small 1 
1  foo one large 2 
2  foo one large 2 
3  foo two small 3 
4  foo two small 3 
5  bar one large 4 
6  bar one small 5 
7  bar two small 6 
8  bar two large 7 
9  foo two large 8 
10 bar one diff -1 
11 bar two diff 1 
12 foo one diff 1 
13 foo two diff 5

提前感谢您的帮助!

hc2pp10m

hc2pp10m1#

diffs = (table.groupby(level="B", axis="columns")
              .diff(-1).dropna(axis="columns")
              .rename(columns={"large": "diff"}, level="C"))

new = table.join(diffs).loc[:, table.columns.get_level_values("B").unique()]
  • groupby列的级别“B”(“一”、“二”...)
  • 从左到右取差(diff(-1))
  • 即计算“大-小”值
  • 因为再远一点就没有了,都是NaN,放弃吧
  • 重命名现在实际上包含差异的“大“
  • 与透视表联接并恢复“一”、“二”的原始顺序

得到

>>> new

B     one              two
C   large small diff large small diff
A
bar     4     5   -1     7     6    1
foo     2     1    1     8     3    5

相关问题