0
$\begingroup$

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!

$\endgroup$

1 Answer 1

1
$\begingroup$

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

enter image description here

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()

enter image description here

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

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

enter image description here

Or:

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

enter image description here

$\endgroup$
1
  • $\begingroup$ 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... $\endgroup$
    – medbz0
    Commented Apr 8, 2021 at 9:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.