我有一个pandas数据框,其中包含20,xxx条公交车登机数据记录。数据集包含一个cardNumber
字段,该字段对于每个乘客都是唯一的。有一个type
字段标识登机类型。有一个routeName
列指定登机发生在哪条路线上,最后是一个Date
列,标识登机发生的时间。我在下面提供了一个模拟数据框架
df = pd.DataFrame(
{'cardNumber': ['999', '999', '999', '999', '901', '901', '888', '888'],
'type': ['trip_pass', 'transfer', 'trip_pass', 'transfer', 'stored_value', 'transfer', 'trip_pass',
'trip_pass'],
'routeName': ['1', '2', '2', '1', '20', '3', '4', '4'],
'Date': ['2020-08-01 06:18:56 -04:00', '2020-08-01 06:46:12 -04:00', '2020-08-01 17:13:51 -04:00',
'2020-08-01 17:47:32 -04:00', '2020-08-10 15:23:16 -04:00', '2020-08-10 15:44:45 -04:00',
'2020-08-31 06:54:09 -04:00', '2020-08-31 16:23:41 -04:00']}
)
df['Date'] = pd.to_datetime(df['Date'])
我想做的是总结一下转移活动。从路线1到路线2或从路线2到路线1的平均换乘次数。数据集中有十一种不同的路由,可以在它们之间进行传输
我希望输出看起来像(注意,下面的输出不是从上面提供的示例生成的):
From | To | Avg. Daily
----------------------------------
1 | 2 | 45.7
1 | 3 | 22.6
20 | 1 | 12.2
如果我答对了问题,您希望从事件中获取行程起点和终点,第一个事件对应于起点(路线名称),然后计算数据集中具有相同起点和终点的车票数量
如果是这样,您可以按如下方式执行此操作
这导致:
正如您所注意到的,最后一个条目具有相同的起点和终点。所以你可能需要过滤掉那些你还没有完整数据的旅行。例如,如果在您的情况下,一条路由永远不能以它开始时的相同routeName结束,您可以通过比较两列来简单地过滤它们
以下代码适用于您提供的区块数据。如果它在您的实际数据中不起作用,请让我知道。也许有更好的方法可以做到这一点,但我认为这是一个很好的起点
这里的总体思路是按乘客分组以确定路线。然后,因为你想要每日平均值,你需要按日期分组,然后按目的地分组,以计算每日平均值
输出:
这里的平均值是1,因为每组只有一个计数。请注意,只考虑了“转移”类型。没有它的,或者没有改变路线的,被进一步移除
相关问题 更多 >
编程相关推荐