Skip to content
Advertisement

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement