Python Forum

Full Version: Multiple MEAN value using FOR loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I use the following code to find MEAN by using For loop,

It displays value for MEAN(5) but, for MEAN(8) it throws an error message - IndexError: list assignment index out of range.

It seems the problem in FOR loop. Can anyone help to fix this issue.

ndays = ([5, 8])
meanALL = ['']

for i in range(len(ndays)):

    meanALL[i] = df.rolling(window=ndays[i]).Price.mean().groupby('Name').head(ndays[i]).dropna()
    print(meanALL[i])
    #i=0
There is no meanAll[1]. You probably want to do this:
ndays = ([5, 8])
meanALL = []
 
for n in ndays:
    meanALL.append(df.rolling(window=n).Price.mean() \
                   .groupby('Name').head(n).dropna())
I get different output if called,

First Option it returns 3 values rather than 2 (duplicate of MEAN(5))
#1
--
ndays = ([5, 8])
meanALL = []

for n in ndays:
meanALL.append(df.rolling(window=n).Price.mean().groupby('Name').head(n).dropna())
print(meanALL)


OUTPUT

[Name
xyz 261.595
Name: Price, dtype: float64]
[Name
xyz 261.595
Name: Price, dtype: float64, Name
xyz 266.723333
Name: Price, dtype: float64]

------------------------------------------------------------------------------------------------
Second Option it returns 1 value (only MEAN(5))rather than 2
#2
==
def funct1(ndays):

SMA = []

for n in ndays:

meanALL.append(df.rolling(window=n).Price.mean().groupby('Name').head(n).dropna())
return meanALL


print(funct1([5, 8]))

OUTPUT

[Name
xyz 261.595
Name: Price, dtype: float64]