vendredi 17 juin 2016

Zero fill data frame forward fill

I am trying to fill a dataframe with zeros, however I do not want to touch leading NaNs:

rng = pd.date_range('2016-06-01', periods=9, freq='D')
df = pd.DataFrame({'data': pd.Series([np.nan]*3 + [20, 30, 40] + [np.nan]*3, rng)})

2016-06-01     NaN
2016-06-02     NaN
2016-06-03     NaN
2016-06-04    20.0
2016-06-05    30.0
2016-06-06    40.0
2016-06-07     NaN
2016-06-08     NaN
2016-06-09     NaN

The df I want after filling/replacing is this:

pd.DataFrame({'data': pd.Series([np.nan]*3 + [20, 30, 40] + [0.]*3, rng)})

2016-06-01     NaN
2016-06-02     NaN
2016-06-03     NaN
2016-06-04    20.0
2016-06-05    30.0
2016-06-06    40.0
2016-06-07     0.0
2016-06-08     0.0
2016-06-09     0.0

Since fillna() only allows value or method and fillna(0) replaces all NaNs, including leading, I was hoping replace could jump in here, but

df.replace([np.nan], 0, method='ffill')

also replaces all NaNs.

How can I zero fill values only after the first non-NaN value, also with multiple data columns?

Aucun commentaire:

Enregistrer un commentaire