python - 将数据框行中的值与前一行进行比较的最佳方法
问题描述
我有一个相当大的df,我需要将一列的差异与前一行中不同列的值相乘。我尝试过使用 iterrows 和 itertuples(令人惊讶的是 iterrows 稍微快了一点),但它并没有达到应有的速度。我想知道是否有更有效的方法来完成这项任务。
这是我到目前为止所拥有的,但我似乎还找不到更好的方法。
def make_decision(df, max_gap):
make_decision = []
new_decision = []
df.sort_values(by=["start_time"])
tod = df.iloc[0]["stop_time"]
for row in df.itertuples(index=False):
toa = row[df.columns.get_loc("start_time")]
if toa - tod > max_gap:
make_decision.append(row[df.columns.get_loc("id")])
new_decision.append(make_decision)
make_decision.clear()
else:
make_decision.append(row[df.columns.get_loc("id")])
curr_tod = row[df.columns.get_loc("stop_time")]
if tod < curr_tod:
tod = curr_tod
if make_decision:
new_decision.append(make_decision)
return new_decision
解决方案
根据方向,您可以使用:
df['start_time'] - df.shift()['stop_time']
或者
df['start_time'] - df.shift(-1)['stop_time']
或互换start_time
和stop_time
。
推荐阅读
- facebook-graph-api - Facebook 广告 - 创建广告创意时出错
- python - python 装饰器如何更改装饰函数中的调用?
- android - RecyclerView 滑动操作而不删除
- c# - 在基类中初始化 ApplicationContext
- c# - C#反序列化自动将字符串反序列化为字节数组以通过自定义代码进行属性?
- javascript - 基于 Three.js 中的新枢轴动画旋转对象
- jenkins - Jenkins 在 git repo 中找不到 sh 脚本
- java - 修复 Java db 与 sqlserver 连接中的“找不到适合 jdbc 的驱动程序”错误
- django - django中的example.com密码重置
- ios - 如何重现罕见的“_CFAutoReleasePoolPop”崩溃?