I have a dataframe like
A B C
1 nan nan
2 nan 5
3 3 nan
4 nan nan
How do I only fill the NULLs (with 0) for each series up until the first non NULL value, leading to
A B C
1 0 0
2 0 5
3 3 nan
4 nan nan
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With