首页 > 解决方案 > 在 python 数据框中的 groupby 上应用具有多个参数的函数,包括来自上一行的值

问题描述

我在名为“td”的数据框中有以下数据:

bookingID          Speed
---------          ------
000000001          10
000000002          20
000000001          30
000000003          40
000000001          50

基本上我需要计算每个 bookingID 的加速度,所以输出必须如下所示:

bookingID          Speed     Acceleration
---------          ------    ------------
000000001          10        0
000000002          20        0
000000001          30        20
000000003          40        0
000000001          50        20

由于某种原因,此代码不起作用:

def get_accel(curr_speed,last_speed):
    return last_speed - curr_speed

td['Acceleration'] = td.groupby(['bookingID']).apply(lambda x: get_accel(td.Speed,td.Speed.shift()))

它说

试图在 DataFrame 中的切片副本上设置一个值。尝试改用 .loc[row_indexer,col_indexer] = value

我究竟做错了什么?谢谢

标签: pythonpandasdataframepandas-groupby

解决方案


首先根据您的输出,这是一个diff问题

td['Acceleration'] = td.groupby('bookingID').Speed.diff().fillna(0)

如果您应用的功能是差异,您可以通过以下方式修复它

td['Acceleration']= td.groupby(['bookingID']).apply(lambda x: get_accel(x.Speed,x.Speed.shift())).reset_index(level=0,drop=True)

推荐阅读