Python:pandas groupby ID,添加多列的值,直到满足中断条件

标签 python pandas pandas-groupby

我有一个数据框

df = pd.DataFrame({ 'id': ['1','1','1','2','2','3','4'],
'transfer_time': [0,10,12,0,19,0,0],
'trip_time': [20,30,9,10,15,12,16],
'is_final_stop': [0,1,0,0,1,1,1]
})
print(df)

如下所示:

id  is_final_stop   transfer_time   trip_time
1   0                 0               20
1   1                 10              30
1   0                 12              9
2   0                 0               10
2   1                 19              15
3   1                 0               12
4   1                 0               16

我需要计算旅程时间 = 转移时间 + 行程时间,按 id 分组,直到 is_final_stop 标志 = 1。(不应考虑将此实例之后的 id 添加到旅程时间)

解决方案应如下所示:

id journey_time
1  60
2  44
3  12
4  16

希望有一个能够在 400 万行数据帧上高效工作的解决方案。干杯。

最佳答案

通过反向cumsum计算“包含”标志,然后在聚合时间上使用GroupBy + sum :

inc_flag = df.iloc[::-1].groupby('id')['is_final_stop'].cumsum().iloc[::-1].astype(bool)

res = df[inc_flag].groupby('id')[['transfer_time', 'trip_time']].sum().sum(1)\
                  .rename('total_time').reset_index()

结果:

  id  total_time
0  1          60
1  2          44
2  3          12
3  4          16

关于Python:pandas groupby ID,添加多列的值,直到满足中断条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257342/

相关文章:

Python组合

python - Scrapy SgmlLinkExtractor

python - 合并两列值上的 Pandas DataFrame,无论行中的顺序如何

python - 在 Python 中为 .csv 文件中的每条记录保存一个新的 .tsv 文件

python - 如何使用 pandas 填充数据框中特定类别数据的缺失数据?

python - 在 Python Pandas 中计算跨数据帧的平均值/平均值

python - 与 itertools.dropwhile 相反(如何在 N 次迭代后停止生成器)

python - 如何循环遍历 pandas groupby 并操作数据?

python Pandas : how to do operations within a group?

python - 如何使用 Format 在 Python 中连接字符串?