如何在python中编写一个条件,仅删除具有2个或更多重复项的重复项
我有一个数据集,它有重复的产品ID。但是,我只想从“Translation”列中删除所有值为“No”的重复项-到目前为止,我有以下内容:如何在python中编写一个条件,仅删除具有2个或更多重复项的重复项,python,pandas,duplicates,conditional-statements,Python,Pandas,Duplicates,Conditional Statements,我有一个数据集,它有重复的产品ID。但是,我只想从“Translation”列中删除所有值为“No”的重复项-到目前为止,我有以下内容: df2 = df.drop_duplicates(subset="Product ID ") 但是,我需要将条件添加到仅删除重复两次以上的产品ID,例如: Product ID | Translation (Column name) 58965 Yes 58965 Yes 58965 N
df2 = df.drop_duplicates(subset="Product ID ")
但是,我需要将条件添加到仅删除重复两次以上的产品ID,例如:
Product ID | Translation (Column name)
58965 Yes
58965 Yes
58965 No
我只想保留前两行,并从上面所示的示例中删除具有条件Translation=No的最后一行。我该怎么写呢
谢谢大家 遗憾的是,我认为您无法使用
drop\u duplicates()
来解决这个问题。我建议使用计数器,当“产品ID”的计数超过2时,开始将其设置为NaN
,然后您可以在最后使用df.dropna()
比如:
from collections import Counter
import numpy as np
c = Counter()
for index, row in df:
pid = row['Product ID']
c[pid] += 1
if c[pid] > 2:
df.loc[index, 'Product ID'] = np.nan
df.dropna(inplace=True)
试试这个:
df.loc[df.groupby('Product ID').cumcount().lt(2)]
尝试这样做:df.loc[df.groupby('Product ID').cumcount().lt(2)]
@rhug123您的答案是正确的。你想把它作为一个答案吗?当然,我会这样做的谢谢@rhug123-因为复制品没有顺序,我忘了提到,另外,我想从这些复制品中至少保留一个,从“翻译”栏中有一个值为“否”的复制品-我将如何在你的答案中写下?df.loc[df.groupby('Product ID').cumcount().lt(2)]在使用Translation
进行编辑的列中,最后一行使用No
。所以你仍然想删除最后一行?谢谢,它起作用了,但是,由于复制没有按顺序进行,我忘了提到,此外,我想从这些复制中至少保留一个,从“Translation”列中有一个值为“No”的复制-我将如何在你的回答中写入?df.loc[df.groupby('Product ID').cumcount().lt(2)]–再次感谢@Rhug123会在上面提供的答案之前添加df=df.sort_值('Translation')
吗?事实上,我不想保留Translation=No-我如何编写保留所有产品ID副本的代码,只有那些Translation=No的产品ID除外?Ty@rhug123