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 C
0 1 0.0 0.0
1 2 0.0 5.0
2 3 3.0 NaN
3 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 C
0 1 0.0 0.0
1 2 0.0 5.0
2 3 3.0 NaN
3 4 NaN NaN
Many ways to skin a cat here :-)