我只想从数据帧中删除特定子集中的重复项。在“A”列中的每个“spec”下,我想删除重复项,但我想在整个数据帧中保留重复项(第一个“spec”下可能有一些行与第二个“spec”下的行相同,但在“spec”下,直到下一个“spec”下我想删除重复项)
这是数据帧
测向
A B C
spec first second
test text1 text2
act text12 text13
act text14 text15
test text32 text33
act text34 text35
test text85 text86
act text87 text88
test text1 text2
act text12 text13
act text14 text15
test text85 text86
act text87 text88
spec third fourth
test text1 text2
act text12 text13
act text14 text15
test text85 text86
act text87 text88
test text1 text2
act text12 text13
act text14 text15
test text85 text86
act text87 text88
这就是我想要的:
测向
A B C
spec first second
test text1 text2
act text12 text13
act text14 text15
test text32 text33
act text34 text35
test text85 text86
act text87 text88
spec third fourth
test text1 text2
act text12 text13
act text14 text15
test text85 text86
act text87 text88
我可以将数据帧拆分为“小”数据帧,然后在for-loop中删除每个“小”数据帧的副本,最后将它们连接起来,但我想知道是否还有其他解决方案。你知道吗
我也试过,成功了:
dfList = df.index[df["A"] == "spec"].tolist()
dfList = np.asarray(dfList)
for dfL in dfList:
idx = np.where(dfList == dfL)
if idx[0][0]!=(len(dfList)-1):
df.loc[dfList[idx[0][0]]:dfList[idx[0][0]+1]-1]
= df.loc[dfList[idx[0][0]]:dfList[idx[0][0]+1]-1].drop_duplicates()
else:
df.loc[dfList[idx[0][0]]:] = df.loc[dfList[idx[0][0]]:].drop_duplicates()
编辑: 我必须在结尾加上:
df.dropna(how='all', inplace=True)
但我只是想知道有没有别的解决办法。你知道吗
这应该起作用:
使用
groupby
+duplicated
:细节
我们使用
cumsum
查找特定“spec”条目下的所有行。组标签包括:然后对该序列进行分组,并计算每组的重复项:
由此,剩下的就是保留那些对应于“False”的行(即,不复制)。你知道吗
另一个可能的解决办法是。。。 您可以拥有一个计数器,并使用计数器值从列a创建一个新的列,只要在列值中遇到spec,就增加计数器值。你知道吗
然后在新列上分组,并删除重复项。你知道吗
相关问题 更多 >
编程相关推荐