【发布时间】:2020-01-18 22:30:39
【问题描述】:
这是我在 StackOverflow 上的第一个问题,所以我尽量做到简洁明了。非常感谢您提前的耐心等待。
背景
我有一个包含 17 个属性的训练数据集,其中包括:origin_station_code、origin_station、destination_station_code、destination_station、route_code、start_time、end_time、fleet_number、@ 987654332@、station、station_type、platform、sch_arr_time、sch_dep_time、act_arr_time、act_dep_time、date。
在这些属性中,我只关心:date、origin_station、destination_station 和 start_time。
该数据集由 61 个单独的 CSV 文件组成,这些文件使用 glob 函数和一个循环组合在一起形成一个超过一百万行的 DataFrame。
DataFrame 的每一行代表火车旅程的一个单独站点。一条完整的路线由多个站点组成,包含 19 个站点的路线示例(Sugar Wave 到 Attempt Pin)如下图所示:here。
通过连接origin_station 和destination_station 属性创建了一个名为complete_route name 的新属性。这可以识别所有的路由,其中有 81 个唯一条目。
任务
我的任务是使用 pandas 对 DataFrame 进行子集化,以便数据集按日期显示 3 条最受欢迎的路线。这个子集 DataFrame 应该显示date、complete_route name,以及该路线每天发生的次数。可以通过将 nunique 方法应用于start_time 属性(日期/时间类型)来确定路线发生的唯一次数。
我目前的进度
目前,我的 GroupBy 和 Aggregate 代码能够显示每条路线每天运行的次数,如下所示:
df_grouped = df.groupby(
['date', 'complete_route_name']
).agg(
{
'start_time': 'nunique' # count the number of unique routes by using the 'nunique' of the start_times
}
).reset_index()
但是,我现在想使用我现有的代码,以便它只显示每天按计数排列的前 3 条唯一路线,例如
date complete_route_name count
2015-08-01 Attempt Pin to Roll Test 101
Suit Treatment Turnback to Spiders Toothbrush 93
Concourse Village to Port Morris 87
2015-08-02 Bridge Bottle to Ants Attempt 119
North Riverdale to Eastchester 117
Wakefield to Kingsbridge 101
......
2015-09-30 Castleton Corners to Dongan Hills 121
Eltingville to Graniteville 119
Great Kills to Castleton 117
对此的任何帮助将不胜感激!
其他资源
如果有任何用途/兴趣,可以在我的GitHub 上找到原始数据集和我当前状态的工作簿。静态工作簿也可以查看here。
非常感谢!
【问题讨论】:
标签: python python-3.x pandas pandas-groupby