Skip to content Skip to sidebar Skip to footer

Get All Rows After The Last Occurrence Of A Specific Value In Pandas

My dataframe looks like ID colA 1 B 1 D 2 B 2 D 2 C I have return all rows after the last occurrence of event B in each group.

Solution 1:

Reverse your rows (this is important). Then call groupby and cumsum, and take all rows with (reversed) cumsum value equal to zero.

df[df.colA.eq('B')[::-1].astype(int).groupby(df.ID).cumsum().eq(0)]

   ID colA
11    D
32    D
42    C

Solution 2:

IIUC

def yourlast(x):
        return x.loc[x.colA.where(df.colA.eq('B')).last_valid_index()+1:]
df.groupby('ID').apply(yourlast)
Out[163]: 
      ID colA
ID           
111    D
232    D
   42    C

Solution 3:

You could do:

ix = (df.colA.eq('B')
        .cumsum()
        .groupby(df.ID)
        .apply(lambda x: x.loc[x.idxmax()+1:]).index.get_level_values(1))

df.loc[ix,:]

    ID colA
11    D
32    D
42    C

Post a Comment for "Get All Rows After The Last Occurrence Of A Specific Value In Pandas"