9951 explained code solutions for 126 technologies


python-numpyGet moving average for Numpy array


import pandas as pd
import numpy as np

data = np.array([1,1,2,3,4,5,3,3,6,6])
d = pd.Series(data)

ma = d.rolling(3).mean()ctrl + c
import numpy as np

load Numpy module for Python

import pandas as pd

load Pandas module

np.array

declare Numpy array

pd.Series

create Pandas series

.rolling(3)

get rolling window object with a specified size (3 elements in our case)

.mean()

calculates moving average

ma

will contain Pandas series with moving averages


Usage example

import pandas as pd
import numpy as np

data = np.array([1,1,2,3,4,5,3,3,6,6])
d = pd.Series(data)

print(d.rolling(3).mean())
output
Rolling [window=3,center=False,axis=0,method=single]
0         NaN
1         NaN
2    1.333333
3    2.000000
4    3.000000
5    4.000000
6    4.000000
7    3.666667
8    4.000000
9    5.000000
dtype: float64