Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用多个参数应用函数,包括python数据帧中groupby上一行的值_Python_Pandas_Dataframe_Pandas Groupby - Fatal编程技术网

使用多个参数应用函数,包括python数据帧中groupby上一行的值

使用多个参数应用函数,包括python数据帧中groupby上一行的值,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我在名为“td”的数据帧中有以下数据: 基本上我需要计算每个bookingID的加速度,所以输出必须如下所示: bookingID Speed Acceleration --------- ------ ------------ 000000001 10 0 000000002 20 0 000000001 30 20 000000003

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

基本上我需要计算每个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()))
上面说

试图在数据帧切片的副本上设置值。 尝试改用.loc[row\u indexer,col\u indexer]=value


我做错了什么?谢谢

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

td['Acceleration'] = td.groupby('bookingID').Speed.diff().fillna(0)
如果应用的函数是diff,则可以通过

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

我更喜欢后者,因为我计划做更复杂的函数。。但是,我得到了以下错误“插入列的索引与框架索引不兼容”,在将参数传递给函数时是否应该使用“x”而不是“td”?@chmscrbbrfck yess直到我得到“插入列的索引与框架索引不兼容”错误,显然它不适用于版本0.12,有任何解决方法吗?我真的很想学习这个,因为我有更复杂的函数要定义。thanks@chmscrbbrfck尝试使用
td['Acceleration']=td.groupby(['bookingID'])。应用(lambda x:get_accel(x.Speed,x.Speed.shift())。重置索引(level=0,drop=True)
@chmscrbbrfck附加读数
td['Acceleration']= td.groupby(['bookingID']).apply(lambda x: get_accel(x.Speed,x.Speed.shift())).reset_index(level=0,drop=True)