Pandas:对每个组独立应用一个函数

Pandas: Applying a function to each group independently

我有以下数据集:

ID      Duration
1          10         
1          20         
1          30
2          5
2          10
2          15
2          20         

我想添加两列,其中第一列是SpeedMean,如果第 i 行中的 Duration 小于 a 的平均持续时间,则它等于 1给定 ID,否则 0.

对于第二列 SpeedMedian,如果第 i 行中的 Duration 小于给定 ID 的中值持续时间,我希望它等于 1,否则为 0。

结果应如下所示:

ID      Duration     SpeedMean    SpeedMedian
1          10           1              1
1          20           0              0
1          30           0              0
2          5            1              1
2          10           1              1
2          15           0              0
2          20           0              0

我知道我应该使用 lambda x,但我是 pandas 的新手,非常感谢您的帮助。

谢谢。

您可以在此处阅读 groupbytransformation

http://pandas.pydata.org/pandas-docs/dev/groupby.html#transformation

In [267]: df['SpeedMean'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.median()).astype(int)

In [268]: df['SpeedMean'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.mean()).astype(int)

In [269]: df['SpeedMedian'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.median()).astype(int)

In [270]: df
Out[270]: 
   ID  Duration  SpeedMean  SpeedMedian
0   1        10          1            1
1   1        20          0            0
2   1        30          0            0
3   2         5          1            1
4   2        10          1            1
5   2        15          0            0
6   2        20          0            0