Pandas- Fill nans up until first non NULL value Pandas- Fill nans up until first non NULL value pandas pandas

Pandas- Fill nans up until first non NULL value


Bit of a trick using pandas.DataFrame.ffill with notna and where:

df.where(df.ffill().notna(), 0)

Or using pandas.DataFrame.interpolate:

df.interpolate('zero', fill_value=0, limit_direction='backward')

Output:

   A    B    C0  1  0.0  0.01  2  0.0  5.02  3  3.0  NaN3  4  NaN  NaN


This would be done using where or mask.

df.mask(df.notna().cumsum().eq(0), 0)# or,df.where(df.notna().cumsum().ne(0), 0)   A    B    C0  1  0.0  0.01  2  0.0  5.02  3  3.0  NaN3  4  NaN  NaN

Many ways to skin a cat here :-)


Since 0 + nan is nan this works:

xf = df.fillna(0) + df.bfill()*0