python - 计算 pandas 中分组的行差异

标签 python pandas numpy

我需要使用 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/

相关文章:

python - Python 中 R 的 seq_len 等价物

python - python/pandas 中长格式数据帧的分箱

python - 正确打印完整阵列

python - 您如何从满足某些条件的数组中随机排除/删除元素?

python - ufunc bitwise_xor 的类型错误

Python 3.x turtle 速度极慢?

python - 编辑许多文本文件的脚本

python - 根据条件在 Pandas 系列中分配值?

python - 如何等待页面自动滚动完成

python - 在没有 VTK 的 python 中对 3D 数据进行插值/子采样