我需要使用 pandas 计算两行之间的差异。
| Group | Value | ID |
----------------------
| M1 | 10 | F1 |
----------------------
| M1 | 11 | F2 |
----------------------
| M1 | 12 | F3 |
----------------------
| M1 | 15 | F4 |
----------------------
示例输出:
----------------------
| M1 | F3 - F2 | 1 |
----------------------
| M1 | F4 - F1 | 5 |
要计算总和,我将使用 pandas.groupby('Group').sum(),但是如何计算行排序很重要的行之间的差异?
最佳答案
我认为您需要使用 apply 的自定义功能它为每个组返回DataFrame
,用于按位置选择 iat
:
def f(x):
#print (x)
a = x['Value'].iat[2] - x['Value'].iat[1]
b = x['Value'].iat[3] - x['Value'].iat[0]
c = x['ID'].iat[2] + ' - ' + x['ID'].iat[1]
d = x['ID'].iat[3] + ' - ' + x['ID'].iat[0]
return pd.DataFrame({'Value': [a,b], 'ID':[c,d]})
df = df.groupby('Group').apply(f).reset_index(level=1, drop=True).reset_index()
print (df)
Group ID Value
0 M1 F3 - F2 1
1 M1 F4 - F1 5
关于python - 计算 pandas 中分组的行差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953594/