Moving average in Pandas

Michelle picture Michelle · Jul 2, 2018 · Viewed 7.4k times · Source

I have a csv file with 3 columns and I want to get the moving average of 1 column. I want to create a new column with the moving average.

import pandas as pd

df= pd.read_csv('csv',usecols=['speed','col2', 'col3'])
df['MA'] = df.rolling( window=5, on='speed').mean
print(df)

It doesnt show me any column anymore. Only the Index and ... .

1   ...
2   ...
3   ...
3   ...
4   ...

[4 rows x 4 columns]

If I change to:

df= df.rolling(window=5, on='speed').mean
print(df)

It only returns me this:

<bound method Rolling.mean of Rolling [window=5,center=False,axis=0,on=speed]>

Process finished with exit code 0

Answer

Sreekiran picture Sreekiran · Jul 3, 2018

Posting one more way.

     df['MA'] = df['speed'].rolling(window=5).mean()