【问题标题】:How to remove rows with multiple occurrences in a row with pandas如何使用熊猫删除一行中多次出现的行
【发布时间】:2021-07-04 10:29:10
【问题描述】:

我有这些数据:

     A  
1    1 
2    1 
3    1  
4    2
5    2
6    1

我希望得到:

     A  
1    1 
-    -   -> (drop)
3    1  
4    2
5    2
6    1

我想删除 col ['A'] 中与一行中出现的相同值的所有行, 但没有第一个和最后一个。

直到现在我都用过:

df = df.loc[df[col].shift() != df[col]]

但它也会删除最后一次出现。

对不起,我的英语不好,提前谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    看起来你和这个问题有同样的问题:Pandas drop_duplicates. Keep first AND last. Is it possible?

    建议的解决方案是:

    pd.concat([
        df['A'].drop_duplicates(keep='first'),
        df['A'].drop_duplicates(keep='last'),
    ])
    

    澄清后更新:

    首先获取您描述的标准的布尔掩码:

    is_last = df['A'] != df['A'].shift(-1)
    is_duplicate = df['A'] == df['A'].shift()
    

    并根据这些删除行:

    df.drop(df.index[~is_last & is_duplicate]) # note the ~ to negate is_last 
    

    【讨论】:

    • drop_duplicates 将删除所有表中具有相同值的所有行,仅当值出现在一行中时才需要删除。
    • 如果我运行代码输出将是:A [1 , 1] [4 , 2] [5 , 2] [6 , 1]
    • 更新了我的答案。
    【解决方案2】:

    基本上你需要对连续的数字进行分组,可以通过diffcumsum来实现:

    print (df.groupby(df["A"].diff().ne(0).cumsum(), as_index=False).nth([0, -1]))
    
       A
    1  1
    3  1
    4  2
    5  2
    6  1
    

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 2018-12-31
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多