我每天有一条公交线路的数据集,有 32 辆公交车和两条 route_direction(0,1)
,第一个方向有 18 个车站,每个车站的 seq 从 1 到 18,另一个方向有 15 个车站,seq( 1-15)并记录进入/退出每个站点的时间。
每条记录包含 bus_id、route_direction、station_seq、in_time、out_time、station_id。
enter image description here
route_id route_direction bus_id station_seq schdeule_date in_time out_time
0 59 1 1349508393 2 2021-01-01 05:04:31 05:04:58
1 59 1 1349508393 2 2021-01-01 05:04:27 05:04:58
2 59 1 1349508393 2 2021-01-01 05:04:31 05:06:31
3 59 1 1349508393 2 2021-01-01 05:04:27 05:06:31
4 59 1 1349508393 1 2021-01-01 05:00:35 05:00:56
首先,我尝试对某个列进行分组,以便为每次旅行提供索引:
grouped = df.groupby(['bus_id','route_direction'])
我在这张图片中得到了类似的信息enter image description here:
index route_id route_direction bus_id station_seq schdeule_date in_time out_time
654 59 0 1349508329 1 2021-01-01 NaN 06:34:10
663 59 0 1349508329 2 2021-01-01 06:33:34 06:34:04
664 59 0 1349508329 2 2021-01-01 06:33:33 06:34:04
677 59 0 1349508329 2 2021-01-01 06:33:34 06:35:34
678 59 0 1349508329 2 2021-01-01 06:33:33 06:35:34
... ... ... ... ... ... ... ...
12133 59 0 1349508329 12 2021-01-01 NaN NaN
如您所见,在几乎相同的日期和时间,在同一站的入口出口处也有相同的 bus_id 重复: 我试过删除重复项,但没有成功:
df = df.drop_duplicates(subset=['bus_id','route_direction','station_seq','station_id','in_time'],keep='first').reset_index(drop=True)
在 in_time 或 out_time 中也有一些 NaN 值,所以如果我放弃了,那么我可能会错过公交线路沿线车站之一的记录。
在一次旅行中对每条公交车记录进行分组以给出 ID 有什么帮助,在这种情况下我如何删除重复的记录(输入时间略有不同)? 任何帮助将不胜感激。