通过汇总组来替换列的值

时间:2019-08-05 17:15:53

标签: python pandas pandas-groupby

假设我具有以下数据框df

   id   x    y        timestamp
   1   32   30        1031
   1   4    105       1035
   1   8    110       1050
   2   18   10        1500
   2   40   20        1550
   2   80   10        1450
....


import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1,1,1,2,2,2], [32,4,8,18,40,80], [30,105,110,10,20,10], [1031,1035,1050,1500,1550,1450]])).T
df.columns = ['id', 'x', 'y', 'timestamp']

我现在有以下代码:

df= df.groupby(["id"]).agg({
    'timestamp': lambda x: x.max() - x.min(),
    'x': 'mean',
    'y': 'mean'
}).reset_index()

不幸的是,这不是我想要的。我想得到以下结果数据框:

id    x     y       timestamp
-----------------------------
1    32     30      19
1    4      105     19
1    8      110     19
2    10     10      100
2    40     20      100
2    80     10      100
....

这意味着时间戳列应替换为每个组的最大值-最小值(但我不想将整个组聚合为一个值)。

这怎么办?

1 个答案:

答案 0 :(得分:2)

IIUC,您只需要transform并使用numpy的peak-to-peak

df['timestamp'] = df.groupby(["id"]).timestamp.transform(np.ptp)