I have the below dataframe:
JavaScript
x
22
22
1
df = pd.DataFrame({'a': [2.85,3.11,3.3,3.275,np.NaN,4.21], 'b': [3.65,3.825,3.475,np.NaN,4.10,2.73],
2
'c': [4.3,3.08,np.NaN,2.40, 3.33, 2.48]}, index=pd.date_range('2019-01-01', periods=6,
3
freq='M'))
4
5
This gives the dataframe as below:
6
a b c
7
2019-01-31 2.850 3.650 4.30
8
2019-02-28 3.110 3.825 3.08
9
2019-03-31 3.300 3.475 NaN
10
2019-04-30 3.275 NaN 2.40
11
2019-05-31 NaN 4.100 3.33
12
2019-06-30 4.210 2.730 2.48
13
14
Expected:
15
a b c
16
2019-01-31 2.850 3.650 4.30
17
2019-02-28 3.110 3.825 3.08
18
2019-03-31 3.300 3.475 **3.69**
19
2019-04-30 3.275 **3.650** 2.40
20
2019-05-31 **3.220** 4.100 3.33
21
2019-06-30 4.210 2.730 2.48
22
I want to replace the NaN values with the 3 month rolling average. How should I got about this?
Advertisement
Answer
If you take NaN
s as 0 into your means, can do:
JavaScript
1
3
1
df.fillna(0,inplace=True)
2
df.rolling(3).mean()
3
This will give you:
JavaScript
1
8
1
a b c
2
2019-01-31 NaN NaN NaN
3
2019-02-28 NaN NaN NaN
4
2019-03-31 3.086667 3.650000 2.460000
5
2019-04-30 3.228333 2.433333 1.826667
6
2019-05-31 2.191667 2.525000 1.910000
7
2019-06-30 2.495000 2.276667 2.736667
8