【问题标题】:How to delete all drop duplicate records and keep only first two using pandas如何使用熊猫删除所有删除重复记录并仅保留前两个
【发布时间】:2020-03-05 15:28:15
【问题描述】:

我有一个包含多个客户交易记录和唯一客户 ID 的数据集。我需要删除除前两条外的所有重复记录。我知道 drop_duplicates 的功能,但我需要弄清楚如何删除除前两个之外的所有内容。

例子

cust_ID  transaction_Date
------   ---------------
abc         01/01/2013
abc         02/09/2013
abc         06/06/2015
abc         09/09/2019
def         02/01/2015
ghi         09/09/2013
def         09/02/2014

我的结果应该是:

cust_ID  transaction_Date
------   ---------------
abc         01/01/2013
abc         02/09/2013
def         02/01/2015
ghi         09/09/2013
def         09/02/2014

这里维护了两条 abc 记录。其他被删除。 def 只有两条记录,两条都被维护,没有被删除。

有什么办法吗?感谢任何轻微的帮助。提前致谢

【问题讨论】:

    标签: python pandas dataframe duplicates pandas-groupby


    【解决方案1】:

    一个简单的head(2)

    df.groupby('cust_ID').head(2)
    
    Out[8]:
      cust_ID transaction_Date
    0     abc       01/01/2013
    1     abc       02/09/2013
    4     def       02/01/2015
    5     ghi       09/09/2013
    6     def       09/02/2014
    

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2015-09-27
      • 1970-01-01
      • 2022-01-23
      • 2019-12-08
      • 2012-04-12
      • 2020-05-14
      • 1970-01-01
      • 2021-03-18
      相关资源
      最近更新 更多