如何最小化行 pandas 数据框中的参数

How to minimize parameter in row pandas dataframe

我有包含公交车站到站预报的数据框:

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]

在这段代码中,我们使用的是字典而不是 pandas 对象,所以这个非常慢。我如何使用 pandas 工具

来做到这一点

以这个数据帧为例

   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 分组、按日期排序和选择最近行的组合。

一个选项 – 删除重复 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()

这会生成一个索引,其中包含“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()

希望有用。