在两行之间减去



我有一个类似的数据集:

name   group   val1  val2  
John    A       3     2     
Cici    B       4     3     
Ian     C       2     2     
Zhang   D       2     1
Zhang   E       1     2
Ian     F       1     2
John    B       2     1
Ian     B       1     2

我做了一个数据透视表,现在看起来是这样的使用这段代码

df_pivot = pd.pivot_table(df, values=['val_1, val_2], index=['name', 'group']).reset_index()
df
name   group   val1  val2  
John    A       3     2     
John    B       2     1     
Ian     C       2     2     
Ian     F       1     2
Ian     B       1     2
Zhang   D       2     1
Zhang   E       1     2
Cici    B       4     3  

在数据透视表之后,我需要计算1)分组名称2)计算组之间的增量。以约翰为例输出应该是:

John    A-B       1     1    
Ian     C-F       1     0
F-B       0     0
B-C       1     0  (the delta is -1, but we only do absolute value)

如何从数据透视表向前移动

让每个组合减去(a-b, a-c, b-c)将不可能直接使用简单的groupby函数。我建议您调整数据并使用自定义函数来计算每种可能的差异组合:

import pandas as pd
import itertools
def combo_subtraction(df, level=0):
unique_groups = df.columns.levels[level]
combos = itertools.combinations(unique_groups, 2)

pieces = {}
for g1, g2 in combos:
name = "{}-{}".format(g1, g2)
pieces[name] = df.xs(g1, level=level, axis=1) - df.xs(g2, level=level, axis=1)
return pd.concat(pieces)
out = (df.pivot(index="name", columns="group") # convert data to wide format
.pipe(combo_subtraction, level=1)       # apply our combination subtraction
.dropna()                               # clean up the result
.swaplevel()
.sort_index())
print(out)
val1  val2
name
Ian   A-B   0.0   0.0
A-C  -1.0   0.0
B-C  -1.0   0.0
John  A-B   1.0   1.0
Zhang A-B   1.0  -1.0

combo_subtraction函数只是遍历"A", "B"one_answers"C"并进行减法运算。然后,它将这些组合的结果粘在一起,形成我们的结果。

最新更新