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

Fill Nan with first Non Nan value above it

I have a dataframe let’s say

df = pd.DataFrame({'first':['fillwithit',None,None,'restbyit', None, None], 'test':[1,2,3,4,5,6]})
>>>In [10]: df
Out[10]: 
        first  test
0  fillwithit     1
1        None     2
2        None     3
3    restbyit     4
4        None     5
5        None     6

What I want is to fill all the None, such that None will look above it, find the first Non-None value, and fill it by it.

For example, None at index 1 and 2 will be filled via fillwithit and 4 & 5 via restbyit.

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

Output should be like

In [12]: df
Out[12]: 
        first  test
0  fillwithit     1
1  fillwithit     2
2  fillwithit     3
3    restbyit     4
4    restbyit     5
5    restbyit     6

I am thinking of a manual for looped version, but it seems inefficient. Do you have any better solution?

>Solution :

just put it here for reference:

import pandas as pd
df = pd.DataFrame({'first':['fillwithit',None,None,'restbyit', None, None], 'test':[1,2,3,4,5,6]})
df = df.ffill()

output:

        first  test
0  fillwithit     1
1  fillwithit     2
2  fillwithit     3
3    restbyit     4
4    restbyit     5
5    restbyit     6
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