1 回答

TA貢獻1856條經(jīng)驗 獲得超11個贊
嘗試這個:
df.groupby(['count', (df['count'] != df['count'].shift()).cumsum()])['response']\
.apply(lambda x: 'NR' if (x.nunique()==1) & (x == 'NR').all() else x.loc[x!='NR'].iloc[0])\
.sort_index(level=1).reset_index(level=1, drop=True)
輸出:
count
1 yes
2 no
3 no
4 NR
5 yes
1 NR
2 NR
3 yes
4 no
5 no
Name: response, dtype: object
細節(jié):
讓我們首先生成一個序列來獲取重復(fù)組:
(df['count'] != df['count'].shift()).cumsum()
使用這個系列以及“計數(shù)”,我們可以創(chuàng)建響應(yīng)組,
如果唯一響應(yīng)的計數(shù)等于 1 并且該響應(yīng)為“NR”,則為該組返回“NR”。否則,使用 返回第一個不是“NR”的響應(yīng)x.loc[X!='NR'].iloc[0]。
添加回答
舉報