Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas- Fill nans up until first non NULL value

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
like image 695
John Avatar asked Nov 01 '19 05:11

John


Video Answer


1 Answers

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
like image 176
Chris Avatar answered Oct 17 '22 08:10

Chris