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

Find value of first occurance in following rows after certain value in row in Pandas

I would like to find value of first occurance after certain value in
row.

Test dataframe:

df = pd.DataFrame({'part': ["Toyota", "basic", "upgraded", "Skoda", "basic", "upgraded","VW", "basic", "upgraded"],
               'id': ["", 1, 2, "",4,5,"",6,7]})
0   Toyota  
1   basic   1
2   upgraded    2
3   Skoda   
4   basic   4
5   upgraded    5
6   VW  
7   basic   6
8   upgraded    7 

I am looking for value for "upgraded" under "Skoda" – thus 5.

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

Any tips how to do this in Pandas dataframe?

Thank you.

>Solution :

You can use boolean indexing with masks:

# locate "upgraded" items
m1 = df['part'].eq('upgraded')

# mask values after the first "Skoda"
m2 = df['part'].eq('Skoda').cummax()

# find all "upgraded" that are after first "Skoda"
# and slice first occurrence
df[m1&m2].iloc[0]

output:

part    upgraded
id             5
Name: 5, dtype: object
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