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

Pandas find last positive value in each column and Replace NaN with that value

I have a dataframe.

import pandas as pd
df = pd.DataFrame({'menu1': [5, 5, 5, 5, 5, None, None], 
                  'menu2': [4, 4, None, 4, None, None, None], 
                  'menu3': [None, None, 9, 9, None, None, None]
                            })
df

For each column, I would like to find the last positive value and replace NAN with that value.

df = pd.DataFrame({'menu1': [5, 5, 5, 5, 5, 5, 5], 
                  'menu2': [4, 4, None, 4, 4, 4, 4], 
                  'menu3': [None, None, 9, 9, 9, 9, 9]
                            })
df

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 :

Using interpolation method pandas.DataFrame.interpolate with specific options:

df.interpolate(limit_direction='forward', limit_area='outside')
  • limit_direction='forward' – tells in what direction NaNs will be filled in
  • limit_area='outside' – tells to only fill NaNs outside valid values (means that NaN should not be surrounded by valid values)

  menu1  menu2  menu3
0    5.0    4.0    NaN
1    5.0    4.0    NaN
2    5.0    NaN    9.0
3    5.0    4.0    9.0
4    5.0    4.0    9.0
5    5.0    4.0    9.0
6    5.0    4.0    9.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