python - 大熊猫填补时间表中缺失的站点
问题描述
我有两个不同的数据框:
第一个数据框存储一些可能的火车连接(如时间表):
index route start stop
0 1 a b
1 1 b c
2 1 c d
3 1 d e
4 2 g h
5 2 h i
6 2 i j
第二个数据框是对实际列车停靠点的测量:
index start stop passengers
0 a b 2
1 b d 4
2 a c 1
3 c d 2
4 g j 5
有时火车不会停在车站。我试图实现的是填补缺失的站点并仍然跟踪乘客测量:
index route start stop passengers
0 1 a b 2
1 1 b c 4
2 1 c d 4
3 1 a b 1
4 1 b c 1
5 1 c d 2
6 2 g h 5
7 2 h i 5
8 2 i j 5
因此,我只想填满所有已跳过的站点。
解决方案
正如 Wen 所指出的,Pandas 可能不是代表此类数据的最佳选择。如果您想使用 Pandas,我建议您从“连接站”通过它们在 df 中的接近度(下一行 = 下一个站,除非它是不同的路线/使用字母来定义顺序)切换到数字标识符并保留路线、名称等在不同的列中。如果您使用数字标识符,这里有一个将乘客相加的可能实现。不同的路线通过 100+站号或 200+站号来区分:
table = pd.DataFrame({'route':['g','g','g','g','r','r','r'],'start':[101,102,103,104,201,202,203],
'stop':[102,103,104,105,202,203,204],'count':[0,0,0,0,0,0,0]})
passenger = pd.DataFrame({'start':[101,102,202],'stop':[104,103,204],
'passenger':[2,5,3]})
count = list(zip(passenger.start.tolist(),passenger.stop.tolist(),passenger.passenger.tolist())) #merge the start, stop and count into one list for each entry
for c in count:
for x in range(c[0],c[1]+1): #go through each stop and add the count to the train table
table['count'] = np.where(table.start == x, table['count'] + c[2], table['count'])
table #Now with the passenger data
推荐阅读
- python - 如何定位在 dask 计算中触发异常的任务提交?
- c - 将 OSX 升级到 Majove 10.14.4 后缺少 C 头文件
- google-cloud-firestore - 有没有办法根据读取的firestore文档触发功能?
- ruby-on-rails - Rails + ActionCable + Passenger + AWS Elasticache (Redis):如何修复“WebSocket 在建立连接之前关闭。” 在生产?
- java - Apache Spark 中 Select DATE_FORMAT(date, format) 的替代方案
- javascript - 使用量角器在页面上切换
- mongodb - Mongodb Atlas Express.js 错误:getaddrinfo ENOTFOUND
- python-3.x - python etcd3随机失败并失败:grpc._channel._Rendezvous:<_Rendezvous of RPC 终止于:status = StatusCode.UNKNOWN
- c# - 为什么在给定“application/json”时 mimeType 没有显示在服务器后端?
- c# - 使用 C# 在 Firebase 数据库中设置序列号节点和子名称