我有截止时间列表list = [16:30:00.100, 16:30:00.200, 16:30:00.350, 16:30:00.450]
。
我的观察如下:
16:30:00.095 A
16:30:00.097 B
16:30:00.122 C
16:30:00.255 D
16:30:00.322 E
16:30:00.420 F
16:30:00.569 G
我要在这里实现的是基于截止时间对观察值进行分组(具体来说,我想查看我的哪个截止时间能够捕获观察值-即第一个截止时间足够快以捕获C,但是太慢了A / B)。所需的输出应如下所示:
cutoff observations captured
16:30:00.100 C
16:30:00.200 D E
16:30:00.350 F
16:30:00.450 G
not possible A B
我尝试使用
pd.cut
,但是它不允许将时间敏感性提高到毫秒,或者至少不是我所知道的。任何帮助将不胜感激。谢谢! 最佳答案
我认为使用cut
的想法很好,也可以将时间数据通过to_timedelta
转换为timedeltas,用fillna
替换不匹配的值并最后汇总join
:
print (df)
time col
0 16:30:00.095 A
1 16:30:00.097 B
2 16:30:00.122 C
3 16:30:00.255 D
4 16:30:00.322 E
5 16:30:00.420 F
6 16:30:00.569 G
df['time'] = pd.to_timedelta(df['time'].astype(str))
L = ['16:30:00.100', '16:30:00.200', '16:30:00.350', '16:30:00.450']
v = pd.to_timedelta(L + [pd.Timedelta.max])
df['b'] = pd.cut(df['time'], bins=v, labels = L)
df['b'] = df['b'].cat.add_categories(['not possible'])
df['b'] = df['b'].fillna('not possible')
print (df)
time col b
0 16:30:00.095000 A not possible
1 16:30:00.097000 B not possible
2 16:30:00.122000 C 16:30:00.100
3 16:30:00.255000 D 16:30:00.200
4 16:30:00.322000 E 16:30:00.200
5 16:30:00.420000 F 16:30:00.350
6 16:30:00.569000 G 16:30:00.450
df2 = df.groupby('b')['col'].apply(', '.join).reset_index()
print (df2)
b col
0 16:30:00.100 C
1 16:30:00.200 D, E
2 16:30:00.350 F
3 16:30:00.450 G
4 not possible A, B
关于python-3.x - 按截止时间分组观察,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55389869/