代码之家  ›  专栏  ›  技术社区  ›  Ze0ruso

如何向数据帧添加条件计数器

  •  0
  • Ze0ruso  · 技术社区  · 4 年前

    我有一个数据框,如下所示:

    id  date       notify
    3   04/09/2019  no
    3   30/10/2019  yes
    3   03/05/2020  no
    3   05/09/2020  no
    3   31/10/2020  yes
    3   03/11/2020  no
    5   03/09/2019  no
    5   27/10/2019  yes
    5   02/05/2020  no
    

    然后,我想对下一行应用相同的数字,其中“notify”将始终是“no”。

    id  date       notify time_group
    3   04/09/2019  no       
    3   30/10/2019  yes       1
    3   03/05/2020  no        1
    3   05/09/2020  no
    3   31/10/2020  yes       2
    3   03/11/2020  no        2
    5   03/09/2019  no
    5   27/10/2019  yes       3
    5   02/05/2020  no        3
    
    

    目前,我尝试了这一点,但没有取得多大成功:

    i = 0
    df['time_grp'] = np.nan
    for row in df.iterrows():
        if row['notify'] == 'yes':
            row['time_group'] = i
            i += 1
    

    1 回复  |  直到 4 年前
        1
  •  2
  •   Quang Hoang    4 年前

    尝试:

    # mark the `yes` rows
    s = df['notify'].eq('yes')
    
    
    # s.cumsum() enumerate the blocks
    # maybe `s.groupby(df['id']).cumsum() if enumeration within id
    df['time_group'] = s.cumsum().where(               # use `where` to keep      
         s |                                           # the `yes` rows
         s.groupby(df['id']).shift(fill_value=False)   # and those after
    )