Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the last row that meets conditions of a mask

This is my dataframe:

df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]})

I want to create column c by using this mask:

mask = (df.a >= df.b)

And I want to get the last row that meets this condition and create column c. The output that I want looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     a   b    c
0   20  20  NaN
1   21  20  NaN
2  333  20  NaN
3  444  20  x

I tried the code below but it didn’t work:

df.loc[mask.cumsum().gt(1) & mask, 'c'] = 'x'

>Solution :

For a mask to flag the last value, use duplicated() by keeping last.

df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]})
mask = (df.a >= df.b)

df['c'] = pd.Series('x', df.index).where(mask & ~mask.duplicated(keep='last'))

A shorter version of @mandy8055’s answer is to call idxmax() to get the index of the highest cum sum (although this is showing a FutureWarning on pandas 2.1.0)

df.loc[mask.cumsum().idxmax(), 'c'] = 'x'

result

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading