Using iterrows() function instead of pd.rolling method

My Code:

sp["avg_5_days"] = sp["Close"].rolling(window=5).mean().shift(1).fillna(0)
sp["avg_30_days"] = sp["Close"].rolling(window=30).mean().shift(1).fillna(0)
sp["avg_365_days"] = sp["Close"].rolling(window=365).mean().shift(1).fillna(0)

Hello there in the project - Predicting Stock Market Price. I am interested to know how to get above output of rolling average of 5, 30, 365 days using iterrows() method. Any help in understanding this would be greatly appreciated.

I looked up this post on stacko as I became curious from your question. From experience I’ve noticed that iterating over each row is going to be timely, and also so confusing. I would just use the built in’s pandas has to offer. Why? I think an easy answer, almost a cop-out is “it’s not Pythonic”. Do what is easy first. Simple is best. The one time I’ve had to use iterows I ended up manually recreating the .melt() method :smiley:

python - How to iterate over rows in a DataFrame in Pandas - Stack Overflow

1 Like

Exactly I looked it over stacko and everyone mentions to never use iterrows on pandas :grinning:. The guidance provided in the project specifies to use iterrows for this specific dataset. I am not sure what would be the reason , I was just curious to see if anyone found it out. But pandas rolling function works in the project and we get the desired result so not really a big let down.