3 回答
TA贡献2003条经验 获得超2个赞
使用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
细节
我们使用cumsum. 组标签是:
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
然后在此系列上完成分组,并计算每组的重复项:
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])
由此,剩下的就是保留对应于“False”的那些行(即不重复)。
TA贡献1804条经验 获得超3个赞
另一个可能的解决方案可能是......您可以拥有一个计数器并从 A 列创建一个带有计数器值的新列,每当您在列值中遇到规范时,您就会增加计数器值。
counter = 0
def counter_fun(val):
if val == 'spec': counter+=1
return counter
df['new_col'] = df.A.apply(counter_fun)
然后在 new_col 上分组,并删除重复项。
添加回答
举报