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

How to get the index of the last condition and assign it to other columns

condition is column ‘A’ > 0.5

I want to calculate the index of the last condition established and assign it to column ‘cond_index’

          A    cond_index
0  0.001566           NaN
1  0.174676           NaN
2  0.553506           2
3  0.583377           3
4  0.418854           3
5  0.836482           5
6  0.927756           6
7  0.800908           7
8  0.277646           7
9  0.388323           7

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

>Solution :

Use Index.to_series with replace missing values if not match condition in Series.where with comapre for greater like 0.5 and last forward filling missing values:

df['new'] = df.index.to_series().where(df['A'].gt(0.5)).ffill()
print (df)
          A  cond_index  new
0  0.001566         NaN  NaN
1  0.174676         NaN  NaN
2  0.553506         2.0  2.0
3  0.583377         3.0  3.0
4  0.418854         3.0  3.0
5  0.836482         5.0  5.0
6  0.927756         6.0  6.0
7  0.800908         7.0  7.0
8  0.277646         7.0  7.0
9  0.388323         7.0  7.0
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