python - Pandas :在 groupby 'date' 中删除重复项

标签 python pandas duplicates unique pandas-groupby

在下面的数据框中,我想消除重复的 cid 值,以便 df.groupby('date').cid.size() 的输出匹配df.groupby('date').cid.nunique() 的输出。

我看过这个post但似乎并没有很好的解决问题的办法。

df = pd.read_csv('https://raw.githubusercontent.com/108michael/ms_thesis/master/crsp.dime.mpl.df')

df.groupby('date').cid.size()

date
2005       7
2006     237
2007    3610
2008    1318
2009    2664
2010     997
2011    6390
2012    2904
2013    7875
2014    3979

df.groupby('date').cid.nunique()

date
2005      3
2006     10
2007    227
2008     52
2009    142
2010     57
2011    219
2012     99
2013    238
2014    146
Name: cid, dtype: int64

我尝试过的事情:

  1. df.groupby([df['date']]).drop_duplicates(cols='cid') 给出了这个错误:AttributeError: Cannot access callable attribute 'drop_duplicates' of ' DataFrameGroupBy' 对象,尝试使用 'apply' 方法
  2. df.groupby(('date').drop_duplicates('cid')) 给出此错误:AttributeError: 'str' object has no attribute 'drop_duplicates'

最佳答案

您不需要 groupby 来基于几列删除重复项,您可以改为指定一个子集:

df2 = df.drop_duplicates(["date", "cid"])
df2.groupby('date').cid.size()
Out[99]: 
date
2005      3
2006     10
2007    227
2008     52
2009    142
2010     57
2011    219
2012     99
2013    238
2014    146
dtype: int64

关于python - Pandas :在 groupby 'date' 中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105609/

相关文章:

python - Discord.py 加载扩展时出现问题

python - Pandas 。复制多索引级别

具有重复项的非数字列的 R 求和值

python - 如何在我的数据框中添加一列来显示哪些企业拥有社交媒体以及哪些企业没有?

python - 如何在 Pandas 中用 NaN 替换浮点值?

url - 是具有多个相邻/重复的 URL

c# - 获取 ListBox 中的所有选中项(包括重复项)

python - 如何用pyscard写智能卡

python - python中的逻辑运算符 "and"

python - 数据流/apache 光束 : manage custom module dependencies