首页 > 解决方案 > 大熊猫填补时间表中缺失的站点

问题描述

我有两个不同的数据框:
第一个数据框存储一些可能的火车连接(如时间表):

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

因此,我只想填满所有已跳过的站点。

标签: pythonpandasmergemissing-datatimetable

解决方案


正如 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

推荐阅读