如何计算 pandas 数据帧中列中两个事件类别之间的转换速度?

How to calculate speed of transitions between two event categories in column in a pandas dataframe?

我有一个 pandas 数据框

ID api_timestamp event_level
0 A9 2022-02-28 13:20:19.305 NaN
1 A9 2022-02-28 13:20:21.703 L1_1
2 A9 2022-02-28 11:54:55.897 L1_2
3 A9 2022-02-28 12:18:00.882 L1_3
4 B1 2022-02-28 12:18:04.882 L1_1
5 B1 2022-02-28 12:18:05.882 L1_6
6 A9 2022-02-28 12:18:07.882 L2_1
7 A9 2022-02-28 12:18:08.882 L1_8

这里我有两个级别 L1 的事件,例如:L1_1、L1_2 和 L2

如何计算每个 ID 的 L1 事件对之间的 L2 事件数

即这里的ID A9,在L1_3和L1_8

之间有一个L2_1

想法是对api_timestamp列进行排序,通过比较L2事件的索引和最大最小索引,找到L1事件之间的L2事件L1 事件。

df['api_timestamp'] = pd.to_datetime(df['api_timestamp'])

for name, g in df.dropna(subset='event_level').sort_values('api_timestamp', ignore_index=True).groupby('ID'):
    l1_indices = g[g['event_level'].str[:2].eq('L1')].index.tolist()
    l2_indices = g[g['event_level'].str.startswith('L2')].index.tolist()
    l2_between = [l2 for l2 in l2_indices if l2 > min(l1_indices) and l2 < max(l1_indices)]
    print(name, len(l2_between))
A9 1
B1 0