【问题标题】:Remove duplicates after a certain number of occurrences出现一定次数后删除重复项
【发布时间】:2020-12-18 09:10:41
【问题描述】:

我们如何过滤下面的数据框以在出现一定次数的 ID 后删除所有重复的 ID 行。 IE。在ID == 0 第三次出现后删除ID == 0 的所有行

谢谢

 pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=['ID', 'Value']).sort_values('ID')
               
                 Output:
                   ID   Value
                    0   7
                    0   8
                    0   5
                    0   5
                ... ... ...
                    9   7
                    9   7
                    9   1
                    9   3

Desired Output for filter_count = 3:

                 Output:
                   ID   Value
                    0   7
                    0   8
                    0   5
                    1   7
                    1   7
                    1   1
                    2   3


                

【问题讨论】:

    标签: python pandas numpy functional-programming data-science


    【解决方案1】:

    如果您想对所有 ID 执行此操作,请使用:

    df.groupby("ID").head(3)
    

    对于单个ID,您可以使用cumcount分配一个新列,然后按条件过滤:

    df["count"] = df.groupby("ID")["Value"].cumcount()
    
    print (df.loc[(df["ID"].ne(0))|((df["ID"].eq(0)&(df["count"]<3)))])
    
        ID  Value  count
    64   0      6      0
    77   0      6      1
    83   0      0      2
    44   1      7      0
    58   1      5      1
    40   1      2      2
    35   1      7      3
    89   1      9      4
    19   1      7      5
    10   1      3      6
    45   2      4      0
    68   2      1      1
    74   2      4      2
    75   2      8      3
    34   2      4      4
    60   2      6      5
    78   2      0      6
    31   2      8      7
    97   2      9      8
    2    2      6      9
    93   2      8     10
    13   2      2     11
    ...
    

    【讨论】:

    • 我想 OP 想要每个 ID 都有这个,所以 df["ID"].eq(0) 可以被删除
    • 我为所有 ID 添加了解决方案。
    【解决方案2】:

    我会做没有 groupby

    df = pd.concat([df.loc[df.ID==0].head(3),df.loc[df.ID!=0]])
    

    【讨论】:

      【解决方案3】:

      谢谢亨利,

      我修改了你的代码,我认为这应该也可以。

      您的df.groupby("ID").head(3) 很棒。谢谢。

      df["count"] = df.groupby("ID")["Value"].cumcount()
      df.loc[df["count"]<3].drop(['count'], axis=1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2014-12-14
        • 1970-01-01
        相关资源
        最近更新 更多