我有公交车站到达预报的数据:
path_id | forecast | forecast_made_at | bus_id
int | datetime | datetime | int我们每5分钟进行一次预测,这样就可以复制数据库条目。例如
In 11:50 we predict bus #11544 will arrive at 11:59
In 11:50 we predict bus #95447 will arrive at 11:55
--......--
In 11:55 we predict bus #11544 will arrive at 12:02我想得到具有最大forecast_made_at参数的最新预测:
res = pd.DataFrame()
for k, row in t_data.iterrows():
prediction = dict(**row)
forecasts = t_data[t_data["bus_id"] == prediction["bus_id"]] # Forecasts with the same bus_id
prediction["best"] = (prediction["forecast_made_at"] == max(forecasts["forecast_made_at"]))
res = res.append(prediction, ignore_index=True)
res = res[res["best"] == True]在这段代码中,我们使用的是字典,而不是熊猫的对象,所以这个非常慢。我怎样才能用熊猫工具做这件事呢?
发布于 2022-01-21 15:39:36
您需要的是按bus_id分组、按日期排序和选择最近的行的组合。
一种选择--删除bus_id复制的副本,并且只保留最近的记录:
t_data.sort_values('forecast_made_at').drop_duplicates(subset=['bus_id'], keep='last')另一个选项:按bus_id分组并选择最后记录:
t_data.sort_values('forecast_made_at').groupby('bus_id').last().reset_index()发布于 2022-01-21 15:37:47
以此数据为例
path_id forecast forecast_made_at bus_id
0 1 2018-01-01 14:10:00 2018-01-01 11:10:00 7
1 1 2018-01-01 14:10:00 2018-01-01 10:15:00 7
2 1 2018-01-01 14:10:00 2018-01-01 10:49:00 7
3 2 2018-09-10 03:05:00 2018-09-09 23:05:00 6
4 2 2018-09-10 03:05:00 2018-09-10 03:00:00 6
5 2 2018-09-10 03:05:00 2018-09-10 01:30:00 6
6 3 2018-04-21 17:32:00 2018-04-21 17:31:00 4
7 3 2018-04-21 17:32:00 2018-04-21 17:12:00 4
8 3 2018-04-21 17:32:00 2018-04-21 17:02:00 4您可以通过以下方法实现这一目标
new_df = df.loc[df.groupby('forecast')['forecast_made_at'].idxmax()]
print(new_df)
path_id forecast forecast_made_at bus_id
0 1 2018-01-01 14:10:00 2018-01-01 11:10:00 7
6 3 2018-04-21 17:32:00 2018-04-21 17:31:00 4
4 2 2018-09-10 03:05:00 2018-09-10 03:00:00 6发布于 2022-01-21 15:47:05
这将生成一个索引,其中包含"bus_id“和该"bus_id”的最大"forecast_made_at“。
ids = df.groupby("bus_id", as_index=False).forecast_made_at.max().set_index(["bus_id", "forecast_made_at"]).index然后,我们可以从原始数据帧中提取匹配此索引的数据,如下所示:
df.set_index(["bus_id", "forecast_made_at"]).loc[ids].reset_index()我希望这是有用的。
https://stackoverflow.com/questions/70803628
复制相似问题