python - 在 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
我究竟做错了什么?谢谢
解决方案
首先根据您的输出,这是一个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)
推荐阅读
- c - 列出所有登录用户并将其保存到 C、linux 中的文本文件中
- git - `git stash`时自动移动子模块文件的任何方法?
- c# - 需要另一个类中的事件处理程序
- entity-framework - 不止一个迁移配置,实体问题
- javascript - 如何在间隔上自动切换 VueJS 选项卡
- javascript - 更改页面时 QML 变量值归零
- npm - yalc "找不到包
我有一个本地 npm 包,我已经对其进行了更改,但是当我尝试将它们添加到我的消费者存储库以使用
yalc add <package>
我收到此消息来测试这些更改时Could not find package <package> in store (/root
- javascript - 使用对象映射数组
- hadoop - 如何从 Yarn Logs on Data 节点手动查找应用 ID?
- reactjs - React:使用标签控件替换输入控件的表单只读模式