3 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
這應(yīng)該有效:
df2 = df.drop_duplicates(subset=['A', 'B','C'])

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
使用groupby+ duplicated:
df[~df.groupby(df.A.eq('spec').cumsum()).apply(lambda x: x.duplicated()).values]
A B C
0 spec first second
1 test text1 text2
2 act text12 text13
3 act text14 text15
4 test text32 text33
5 act text34 text35
6 test text85 text86
7 act text87 text88
13 spec third fourth
14 test text1 text2
15 act text12 text13
16 act text14 text15
17 test text85 text86
18 act text87 text88
細(xì)節(jié)
我們使用cumsum. 組標(biāo)簽是:
df.A.eq('spec').cumsum()
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 2
14 2
15 2
16 2
17 2
18 2
19 2
20 2
21 2
22 2
23 2
Name: A, dtype: int64
然后在此系列上完成分組,并計(jì)算每組的重復(fù)項(xiàng):
df.groupby(df.A.eq('spec').cumsum()).apply(lambda x: x.duplicated()).values
array([False, False, False, False, False, False, False, False, True,
True, True, True, True, False, False, False, False, False,
False, True, True, True, True, True])
由此,剩下的就是保留對(duì)應(yīng)于“False”的那些行(即不重復(fù))。

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
另一個(gè)可能的解決方案可能是......您可以擁有一個(gè)計(jì)數(shù)器并從 A 列創(chuàng)建一個(gè)帶有計(jì)數(shù)器值的新列,每當(dāng)您在列值中遇到規(guī)范時(shí),您就會(huì)增加計(jì)數(shù)器值。
counter = 0
def counter_fun(val):
if val == 'spec': counter+=1
return counter
df['new_col'] = df.A.apply(counter_fun)
然后在 new_col 上分組,并刪除重復(fù)項(xiàng)。
添加回答
舉報(bào)