Pandas Python 算法想法

2024-04-25 08:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

实际的pandas数据集如下所示:

index household carID   waypoint

497   201248    2       from home       15
498   201248    2                       18
499   201248    2       to home         19
500   201248    1       from home       10
501   201248    1       to home         10
502   201248    1                       19
503   201248    1       to home         0
504   201248    2       from home       8
505   201248    2                       9
506   201248    2       to home         9

这里你看到,carID110:000:00。所以缺席14小时:

对于carID2来说,情况变得很复杂。从8:009和从15:0019:00都没有

我想要的是计算CarID2的缺席时间:从第一次驱动from home08:00,到最后一次驱动to home19:00。你知道吗

所以最终的数据帧应该是这样的:

index household carID   waypoint            absent
497   201248    2       from home       15   
498   201248    2                       18
499   201248    2       to home         19   4
500   201248    1       from home       10
501   201248    1       to home         10
502   201248    1                       19
503   201248    1       to home         0    14
504   201248    2       from home       8
505   201248    2                       9
506   201248    2       to home         9    11 (because the final end time is 19:00 see upper table)

有人有主意吗?如果我能在特定的家庭号码(而不是索引)内进行排序,这会有所帮助。你知道吗


Tags: to数据frompandashomeindex情况小时
1条回答
网友
1楼 · 发布于 2024-04-25 08:45:10

我把你的数据框的第四栏命名为“时间”。你知道吗

df['time_24'] = df['time'] # a new column having times from 01 to 24 instead of 00
df.loc[df['time'] == 0, 'time_24'] = 24 # replacing 00 with 24
df.join(df.groupby('carID')['time_24'].max() - df.groupby('carID')['time_24'].min(), on='carID', rsuffix='_r')
df['absent'] = df['time_24_r']

缺席列返回您想要的时间。这项工作假设的逻辑,从家时间的最小值总是小于最大的到家时间。否则,您也需要按航路点分组。你知道吗

相关问题 更多 >