Pandas Duplicate()一次返回除一行以外的所有重复项

2024-09-29 19:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力争取所有自1901-2016年以来不止一次获奖的诺贝尔奖获得者。我尝试了pandasduplicate()方法,但它只返回一次所有重复项,除了一行或一项。我根据数据帧中的full_name列获取重复项。我尝试了不同的参数组合,但得到了相同的结果。我知道我可以手动删除这一行,但这里发生了什么错误。我的代码如下所示

Try-1

lucky_winners = df[df.duplicated(['full_name'])]

Try-2

lucky_winners = df[df.duplicated(['full_name'], keep='first')]

Try-3

lucky_winners = df[df.duplicated(['full_name'], keep='last')]

相同输出:

lucky_winners.full_name

62                           Marie Curie, née Sklodowska
215    Comité international de la Croix Rouge (Intern...
340                                   Linus Carl Pauling
348    Comité international de la Croix Rouge (Intern...
424                                         John Bardeen
505                                     Frederick Sanger
523    Office of the United Nations High Commissioner...

复制的实体是Comité international de la Croix Rouge (International Committee of the Red Cross)。我甚至检查了它们的布尔比较,得到了True。使用

lucky_winners.iloc[1].full_name == lucky_winners.iloc[3].full_name

我不明白到底哪里出了问题


Tags: namedfdelafulltrykeepintern
2条回答

如果要查找具有多个匹配项的所有唯一值,一种方法是使用带有可选return_counts=True参数的^{}。结果元组(unique, counts)可以组合使用,以查找计数超过1的所有唯一值:

In [3]: # mash keys to get a series with repeated values
   ...: s = pd.Series(list('abcoiansfaionawiaonwncawowc'))

In [4]: # get unique values and counts
   ...: u, c = np.unique(s, return_counts=True)

In [5]: # find all unique keys with occurrence counts > 1
   ...: u[c > 1]
Out[5]: array(['a', 'c', 'i', 'n', 'o', 'w'], dtype=object)

因此,我所做的是在不重复的情况下获得所有的副本(先把问题再读一遍):

  • 已获取具有多个引用的所有重复项

    lucky_winners = df[df.duplicated(['full_name'])]

  • 然后从这个新创建的数据帧中删除重复项

    lucky_winners.drop_duplicates(subset = ['full_name'], inplace=True)

就这些!通过这种方式,我得到了所有重复的行,没有重复

相关问题 更多 >

    热门问题