如何最小化熊猫数据帧行中的参数



我有公共汽车站到达预测的数据帧:

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]

在这段代码中,我们使用的是字典,而不是panda对象,所以这段代码非常慢。我如何使用熊猫工具做到这一点

您需要的是按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()

使用此数据帧作为示例

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

这会生成一个包含";bus_id";并且最大";forecast_made_at";为此";bus_id";

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()

我希望这是有用的。

最新更新