# Pandas rolling mean not working properly [closed]

I have the following dataframe df on which I want to compute a 4-window moving average :

2000-01-03     NaN
2000-01-04     NaN
2000-01-05    -5.0
2000-01-06    1.40
2000-01-07    0.47


I want the following output:

2000-01-03     NaN
2000-01-04     NaN
2000-01-05     NaN
2000-01-06    -1.8
2000-01-07    -1.04


With df.rolling(4).mean(), I get

2000-01-03     NaN
2000-01-04     NaN
2000-01-05     NaN
2000-01-06     NaN
2000-01-07     NaN


By setting the parameter min_periods=1, I get

2000-01-03     NaN
2000-01-04     NaN
2000-01-05    -5.0
2000-01-06    -1.8
2000-01-07    -1.04


How do I get rid of NaNs outside my rolling window?

Thanks!

This is not at all a quantitative finance question and will probable be moved to StackExchange, but in any case...

import pandas as pd
import numpy as np

df = pd.DataFrame([np.nan, np.nan, -5.0, 1.4, 0.47])
df


The NaN values are expected for the first periods, since there are not enough elements to compute the rolling window. To get what you want, you could use:

df.rolling(4, min_periods=2).mean()


If you really want to remove the NaN values from you result, you can just do:

df.rolling(4, min_periods=2).mean().dropna()


Or:

df.rolling(4, min_periods=2).mean().fillna(0)


• Thanks! But this would mean groping for ways to find out the right min_periods parameter for each column, assuming I have an entire whole dataframe... – medbz0 Apr 8 at 9:51