桃花長(zhǎng)相依
2023-10-26 10:36:57
如果值 Positive 在我的 pandas 數(shù)據(jù)框中連續(xù)出現(xiàn)超過 2 次(變?yōu)?Negative),我需要更改數(shù)據(jù)集的值,并且如果它是不同的 id,我也需要按 id 設(shè)置 id。如果Negative 在行循環(huán)中中斷超過2 次,或者Negative 在一行中出現(xiàn)超過2 次,則不執(zhí)行任何操作。例子: id status0 3 Positive1 3 Positive2 3 Positive3 2 Positive4 1 Positive5 2 Positive 6 2 Positive7 2 Positive得到的 df 應(yīng)該是: id status0 3 Positive1 3 Positive2 3 Negative3 2 Positive4 1 Positive5 2 Positive 6 2 Negative7 2 Negative
1 回答

慕田峪7331174
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
我們可以使用來(lái)計(jì)算, thengroupby().cumcount()的出現(xiàn)次數(shù):idnp.where
mask = (df['status'].eq('Positive') # check for positive
.groupby(df['id']) # group by id
.transform(lambda x:x.rolling(3).sum()) # count the consecutive positive in the last 3
.eq(3)
)
df.loc[mask, 'status'] = 'Negative'
輸出:
id status
0 3 Positive
1 3 Positive
2 3 Negative
3 2 Positive
4 1 Positive
5 2 Positive
6 2 Negative
7 2 Negative
添加回答
舉報(bào)
0/150
提交
取消