python - 如何在熊猫数据框中找到最后一个事件的日期
问题描述
我有一个 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
我如何计算这一列?
解决方案
您可以transform
与事件一起使用cumsum
df['time_of_last_event']=df.groupby(df.event.cumusm()).time.transform('first')
推荐阅读
- javascript - 如何在 React 中为一个组件打开更多视图并关闭其他组件?
- php - 使用 aws/aws-sdk-php 的“Amazon Personalize”PutItems、PutEvents、PutUsers
- java - 在 List 和 HashMap 之间使用 retainAll() 函数的时间复杂度是多少?
- python - 用于检查数字是否为素数的 Python 函数
- python - Pandas 在不同的列中对具有相同值的不同行进行分组
- sql - 如何从 SQL XML 列中提取值列表
- python - 在 python-3.x 之后如何打印并使程序不执行任何操作
- reactjs - 无法覆盖 react-date-picker 中的样式
- java - 无法弄清楚我的 getter 方法哪里出错了(Java)
- asp.net - 动态循环模型项