我有一個資料框,如下所示:
id date notify
3 04/09/2019 no
3 30/10/2019 yes
3 03/05/2020 no
3 05/09/2020 no
3 31/10/2020 yes
3 03/11/2020 no
5 03/09/2019 no
5 27/10/2019 yes
5 02/05/2020 no
我想為每次“通知”為“是”時創建一個計數器組編號。然后我想將相同的數字應用于下一行,其中“通知”將始終為“否”。
它應該是這樣的:
id date notify time_group
3 04/09/2019 no
3 30/10/2019 yes 1
3 03/05/2020 no 1
3 05/09/2020 no
3 31/10/2020 yes 2
3 03/11/2020 no 2
5 03/09/2019 no
5 27/10/2019 yes 3
5 02/05/2020 no 3
目前我已經嘗試過但沒有取得多大成功:
i = 0
df['time_grp'] = np.nan
for row in df.iterrows():
if row['notify'] == 'yes':
row['time_group'] = i
i = 1
我想知道是否有更熊貓友好的方式來實作這一點?也許利用 cumcount()?我知道然后我可以使用 shift(-1) 將相同的計數器組號應用于下一行......
uj5u.com熱心網友回復:
嘗試:
# mark the `yes` rows
s = df['notify'].eq('yes')
# s.cumsum() enumerate the blocks
# maybe `s.groupby(df['id']).cumsum() if enumeration within id
df['time_group'] = s.cumsum().where( # use `where` to keep
s | # the `yes` rows
s.groupby(df['id']).shift(fill_value=False) # and those after
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344555.html
下一篇:當所有運算式都在regex101.com上作業時,Python正則運算式不起作用,當試圖將8"W->8"W和8"otherword->8"其他單詞
