То же самое или нет, можно достичь с помощью np.unique
.
df1 = df.groupby(['cid','e']).agg({'tp':lambda x: np.unique(x)})
df1['result'] = df1['tp'].apply(lambda x: type(x) is not np.ndarray)
tp result
cid e
A 1 1 True
2 2 True
3 [3, 4, 5] False
B 3 23 True
4 24 True
5 [25, 26, 27] False
C 1 28 True
2 29 True
D 1 30 True
2 31 True
3 32 True
4 33 True
Добавить счетчик можно с помощью cumcount()
.
df1= df1[df1['result']]
df1['tp'] = df1['tp'].astype(int)
df1['result'] = df1.groupby('result').cumcount()+1
tp result
cid e
A 1 1 1
2 2 2
B 3 23 3
4 24 4
C 1 28 5
2 29 6
D 1 30 7
2 31 8
3 32 9
4 33 10
Наконец, объедините ихи заполните 0.
df1 = df1.reset_index()
df = pd.merge(df,df1,on=['cid','e','tp'],how='left').fillna(0)