尝试标记每个组中的第一次相遇 pandas

Trying to mark first encounter in every group pandas

我有一个包含 5 列的 df:

我想做的是在与每个特定群体的人交谈后标记第一次客户互动的价值。

希望结果是这样的:

我尝试过的是移动类型列,将前一行放在类型前面,以检查其客户和前一行是否为人类。但是,我想不出一个分组选项来为每次出现的每个组获取最小索引。

这个有效:

k = pd.DataFrame(df.groupby('group').apply(lambda g: (g['type'].eq('customer') & g['type'].shift(1).eq('human')).pipe(lambda x: [x.idxmax(), x[::-1].idxmax()])).tolist())

df['First'] = ''
df['Last'] = ''

df.loc[k[1], 'First'] = 'F'
df.loc[k[1], 'Last'] = 'L'

输出:

>>> df
   group      type First Last
0      x       bot           
1      x  customer           
2      x       bot           
3      x  customer           
4      x     human           
5      x  customer     F     
6      x     human           
7      x  customer          L
8      y       bot           
9      y  customer           
10     y       bot           
11     y  customer           
12     y     human           
13     y  customer     F     
14     y     human           
15     y  customer          L
16     z       bot           
17     z  customer           
18     z       bot           
19     z  customer           
20     z     human           
21     z  customer     F     
22     z     human           
23     z  customer          L
24     z  customer           
25     z  customer