Python Forum

Full Version: Newbie question on how to use pandas.rolling_mean
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import pandas as pd

data = [1.0, 2.0, 3.0, 4.0]
rollmean_data_2 = pd.rolling_mean(data, 2)
print(rollmean_data_2)
I want to learn how to use rolling_mean by pandas, the pandas version is 0.21.0.
But when I run the above code, I got the following error:
AttributeError: 'list' object has no attribue 'rolling'
Please show me how to use pandas.rolling_mean
Or if other python package has the similar function, please also advise how to use them.
Thanks,
http://pandas.pydata.org/pandas-docs/ver..._mean.html
Docs suggest that your data argument must be of type Series or DataFrame. List is not accepted, which is what your error message tells.
import pandas as pd

data = [1.0, 2.0, 3.0, 4.0]
s1 = pd.Series(data)
rollmean = pd.rolling_mean(s1, 2)
print(rollmean)
Hello, I changed my code according to your advice, but I got some warning:
Warning: pd.rolling_mean is deprecated for Series and will be removed in a future version, replace with
Series.rolling(window=2, center=False).mean()

However, I did see the result:
0 NaN
1 1.5
2 2.5
3 3.5
dtype: float64

I want to know how to use the new version or the version in future to do the same job.
Another issue is: the first value is: NaN
How I can either delete the first value or replace the value NaN by another value, i.e. 0.0
Thanks,
Warning tells you which function to use instead of rolling_mean. Replace it with Series.rolling. Search online or check in docs to find out how to use it. If you won't be able to get it to work, post again with code and error message.
About removing NaNs or replacing them with another value, it's very easy to find answer to that using your favourite search engine. So again, try it and post back if it won't work.
from numpy import *
import numpy as np
import pandas as pd

data = [1.0, 2.0, 3.0, 4.0]
s1 = pd.Series(data)
rollmean = pd.Series.rolling(s1, 2).mean()
#print(rollmean)
filled0 = [0.0 if isnan(item) else item for item in rollmean]
print(filled0)
Great, I have figured it out with the above code.
Thanks,
I'm glad you got it working!
Check out this function which is already impelemented, you may find it a more elegant solution ;)
https://pandas.pydata.org/pandas-docs/st...illna.html