[英]subtract between two rows
I have a dataset similar to this:我有一个类似的数据集:
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
I did a pivot table and it now looks like this using this piece of code我做了一个 pivot 表,现在使用这段代码看起来像这样
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
After the pivot table, I need to calculate 1) groupby name 2) calculate the delta between groups.在 pivot 表之后,我需要计算 1) groupby name 2) 计算组之间的增量。 Take John as an example The output should be:
以约翰为例 output 应该是:
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)
How to move forward from my pivot table如何从我的 pivot 表继续前进
Getting each combination to subtract (ab, ac, bc) won't be directly possible with a simple groupby
function.使用简单的
groupby
function 无法直接将每个组合减去(ab,ac,bc)。 I suggest that you pivot your data and use a custom function to calculate each combination of possible differences:我建议您使用 pivot 您的数据并使用自定义 function 来计算可能差异的每种组合:
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
The combo_subtraction
function simply iterates over all possible combinations of 2 of "A", "B", and "C" and performs the subtraction operation. combo_subtraction
function 简单地迭代“A”、“B”和“C”中 2 个的所有可能组合并执行减法运算。 It then sticks the results of these combinations back together forming our result.然后,它将这些组合的结果重新组合在一起,形成我们的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.