【问题标题】:How to 'write-back' the result of an aggregation to the main data frame如何将聚合结果“写回”到主数据帧
【发布时间】:2020-12-22 01:10:33
【问题描述】:

注意:这个问题和这个问题类似:find duplicate rows in a pandas dataframe,已经有了很好的答案。但是,我想在这里关注这个问题的“后半部分”,它讨论了将“重复组”写回主数据帧的最佳方法。


我的数据如下所示:

file            md5
myfile.mov      9ee8
teller.mov      2udi
seven.mov       9ee8

我想要一个名为 dupe_md5_group 的新字段,如果 count(*) > 1 则为 md5,否则为 None。这是我目前正在做的事情:

df2=pd.DataFrame([{'file': 'myfile.mov', 'md5': '9ee8'}, {'file': 'teller.mov', 'md5': '2udi'}, {'file': 'seven.mov', 'md5': '9ee8'}])

# get all the duplicate md5s as a set which we can later look up
duplicate_md5s = set(df2[['md5']].groupby('md5').filter(lambda x: len(x) > 1).md5)

# write back the duplicate results to the main dataframe with a new column if a dupe
df2['dupe_md5_group'] = df2['md5'].apply(lambda md5: None if md5 not in duplicate_md5s else md5)

#          file   md5           dupe_md5_group
# 0  myfile.mov  9ee8           9ee8
# 1  teller.mov  2udi           None
# 2   seven.mov  9ee8           9ee8

它有效,但它似乎超级笨拙。有没有更好的方法来做到这一点?

【问题讨论】:

  • 这能回答你的问题吗? find duplicate rows in a pandas dataframe
  • @RichieV 有点——是的,它解决了两个语句中的第一个。但根本不是真正的回写。实际上答案实际上只是删除了所有其他行,所以我认为这个问题略有不同,虽然是的,我可以更改它并参考它,如果你重新打开它。
  • 你的问题仍然悬而未决,这只是一个建议.. 但它确实解释了如何用series.duplicated() 解决这个问题,看看series.where 的新专栏

标签: python pandas


【解决方案1】:

重复使用np.where

df['dupe_md5_group'] = np.where(df['md5'].duplicated(keep=False), df['md5'], None)

         file   md5 dupe_md5_group
0  myfile.mov  9ee8           9ee8
1  teller.mov  2udi           None
2   seven.mov  9ee8           9ee8

【讨论】:

  • 谢谢,太好了。也比建议的副本更有效率。
猜你喜欢
  • 2018-11-08
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多