我有一個 df 有 5 列:

我想做的是在與每個特定群體的人交談后標記第一次客戶互動的價值。
希望結果是這樣的:

我嘗試的是移動型別列,將前一行放在型別前面,以檢查其客戶和上一行是否是人類。但是,我無法找出一個分組選項來獲取每個組每次出現的最小索引。
uj5u.com熱心網友回復:
這有效:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444020.html
標籤:熊猫 熊猫-groupby
