首页 > 解决方案 > 如何在熊猫数据框中找到最后一个事件的日期

问题描述

我有一个 Pandas DataFrame,如下所示:

                    time     event
0    2018-12-30 02:15:00      True
1    2018-12-30 05:33:00     False
2    2018-12-30 08:53:00     False
3    2018-12-30 12:06:00      True
4    2018-12-30 15:23:00      True 
5    2018-12-30 20:18:00     False
6    2018-12-30 22:01:00     False

我需要计算一列“最后一个事件的时间”。这需要返回“True”事件的最新日期时间。

即,在上面的例子中,结果应该是这样的:

                    time      event     time_of_last_event     
0    2018-12-30 02:15:00      True     2018-12-30 02:15:00
1    2018-12-30 05:33:00     False     2018-12-30 02:15:00
2    2018-12-30 08:53:00     False     2018-12-30 02:15:00
3    2018-12-30 12:06:00      True     2018-12-30 12:06:00
4    2018-12-30 15:23:00      True     2018-12-30 15:23:00 
5    2018-12-30 20:18:00     False     2018-12-30 15:23:00
6    2018-12-30 22:01:00     False     2018-12-30 15:23:00

我如何计算这一列?

标签: pythonpandas

解决方案


您可以transform与事件一起使用cumsum

df['time_of_last_event']=df.groupby(df.event.cumusm()).time.transform('first')

推荐阅读