【问题标题】:How to remove rows based on next value in a sequence? (pandas)如何根据序列中的下一个值删除行? (熊猫)
【发布时间】:2021-12-14 03:48:49
【问题描述】:

我有以下数据框:

id  date       outcome
3   03/05/2019  no
3   29/05/2019  no
3   04/09/2019  no
3   30/10/2019  yes
3   03/05/2020  no
5   03/12/2019  no
5   26/12/2019  no
5   27/01/2020  yes
5   03/06/2020  yes
6   04/05/2019  no
6   27/10/2019  no
6   26/11/2019  yes
6   28/11/2019  yes
6   29/11/2019  yes
6   20/12/2019  yes
6   27/12/2019  yes
6   29/12/2019  yes
6   03/01/2020  yes
6   14/01/2020  yes
6   11/02/2020  yes
6   13/02/2020  yes
6   18/02/2020  yes
6   13/04/2020  yes
6   14/04/2020  yes
6   24/04/2020  yes
6   30/04/2020  yes
6   05/05/2020  no

它根据 id 和按日期升序分组。

如果后面的行具有相同的结果,我想删除该行。这是 id 3 的预期结果:

id  date       outcome
3   04/09/2019  no
3   30/10/2019  yes
3   03/05/2020  no

目前我已经创建了一个这样的面具:

m1 = (df['alerts'] == df['alerts'].shift(-1))

但不确定接下来我需要做什么来应用条件并删除指定的行。我假设我将使用 id 列进行分组...

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    让我们做

    m1 = (df['outcome'] !=
          df['outcome'].shift()).cumsum()
    out = df.groupby([df['id'],m1]).head(1)
        id        date outcome
    0    3  03/05/2019      no
    3    3  30/10/2019     yes
    4    3  03/05/2020      no
    5    5  03/12/2019      no
    7    5  27/01/2020     yes
    9    6  04/05/2019      no
    11   6  26/11/2019     yes
    26   6  05/05/2020      no
    

    【讨论】:

      【解决方案2】:

      这能解决您的问题吗?

      new_df = pd.DataFrame()
      current = "yes"
      for i, row in df.iterrows():
          if row['outcome'] != current:
              current = row['outcome']
              new_df = new_df.append(row)
      

      【讨论】:

      • 请为您的回答提供更多详细信息。简单地说“这能解决你的问题吗?” 是不够的。您可以说明这是如何工作的,以及可以修改哪些内容等。
      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2016-05-07
      • 1970-01-01
      相关资源
      最近更新 更多