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
Post a Comment for "Get All Rows After The Last Occurrence Of A Specific Value In Pandas"