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 fill the nan's at the end of every column with 0's in pandas python?

I want to forward fill my dataframe with a custom value – like 0. But pandas dosent allow to ffill with custom value. It only takes the last available value in every column and fills the nan values at the end with it. So was wondering if there was a better way to do this in python.

df = 

nan  1  2  nan
1    4  5  2
nan  6  7  nan
nan  nan 8 nan
nan  nan 8 nan

Expected Output:

nan  1  2  nan
1    4  5  2
0    6  7  0
0   0  8   0
0   0  8   0

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 :

Let us do

df = df.where(df.ffill().isna() | df.notna(),0)
Out[108]: 
     1    2  3    4
0  NaN  1.0  2  NaN
1  1.0  4.0  5  2.0
2  0.0  6.0  7  0.0
3  0.0  0.0  8  0.0
4  0.0  0.0  8  0.0

Or

df.fillna(0).mask(df.ffill().isna())
Out[111]: 
     1    2  3    4
0  NaN  1.0  2  NaN
1  1.0  4.0  5  2.0
2  0.0  6.0  7  0.0
3  0.0  0.0  8  0.0
4  0.0  0.0  8  0.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