【问题标题】:Delete rows from a pandas DataFrame based on a conditional expression, iteration (n) and (n+1)根据条件表达式、迭代 (n) 和 (n+1) 从 pandas DataFrame 中删除行
【发布时间】:2020-05-25 23:13:32
【问题描述】:

给定一个数据框如下:

 col1 
1  0.6   
2  0.88  
3  1.2  
4  1.2  
5  1.2  
6  0.55  
7  0.55
8  0.65

我想从中删除行 (n+1) 中的值与 (n) 中相同的值 的行,这样会产生:

col1 
1  0.6   
2  0.88  
3  1.2  
4  row deleted  
5  row deleted  
6  0.55  
7  row deleted
8  0.65

【问题讨论】:

  • 你可以使用任何建议的解决方案,如果你想要 NaN,可以使用df = df.mask(df['col1'].eq(df['col1'].shift(1)))

标签: python pandas dataframe iteration


【解决方案1】:
In [191]: df[df["col1"] != df["col1"].shift()]
Out[191]:
   col1
1  0.60
2  0.88
3  1.20
6  0.55
8  0.65

【讨论】:

    【解决方案2】:

    好吧,让我们做吧

    df=df[df.diff().ne(0)]
    

    【讨论】:

      【解决方案3】:

      试试这个:

      df = df[~df['col1'].eq(df['col1'].shift(1))]
      print(df)
      
         col1
      0  0.60
      1  0.88
      2  1.20
      5  0.55
      7  0.65
      

      或者:

      df = df[df['col1'].ne(df['col1'].shift(1))]
      print(df)
      
         col1
      0  0.60
      1  0.88
      2  1.20
      5  0.55
      7  0.65
      

      【讨论】:

      • 第二种方法不行,比如1,1,2,1,1 .....应该是1,2,1
      • 我不明白,drop_duplicates方法中默认没有keep='first'
      • 是的,但是 drop_duplicates 没有考虑到它们必须是连续的
      • 我认为df = df[~df['col1'].eq(df['col1'].shift(1))] 是解决方案,或者如果您不想概括为字符串,则@WenYoBen 的解决方案
      • 好的,知道了。有道理。
      猜你喜欢
      • 2014-02-06
      • 2020-10-27
      • 2018-01-11
      • 2014-06-11
      • 2022-06-21
      • 2022-01-14
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多