Python Forum
Multiple MEAN value using FOR loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple MEAN value using FOR loop
#1
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
Reply
#2
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())
Reply
#3
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to loop through code to plot seaborn line plots across multiple subplots eyavuz21 0 1,657 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
  Multiple Loop Statements in a Variable Dexty 1 1,200 May-23-2022, 08:53 AM
Last Post: bowlofred
  Multiple user defined plots with secondary axes using for loop maltp 1 1,441 Apr-30-2022, 10:19 AM
Last Post: maltp
  Trying to separate a loop across multiple threads stylingpat 0 1,671 May-05-2021, 05:21 PM
Last Post: stylingpat
Question How to print multiple elements from multiple lists in a FOR loop? Gilush 6 2,926 Dec-02-2020, 07:50 AM
Last Post: Gilush
  How to Display Multiple Time Tables With While Loop ZQ12 2 2,159 Nov-10-2019, 04:15 AM
Last Post: ZQ12
  pytest loop through multiple tests? burvil 0 4,314 Sep-26-2019, 11:42 PM
Last Post: burvil
  Pasting multiple images on to one image with a for loop. DreamingInsanity 2 6,471 Feb-01-2019, 12:39 PM
Last Post: DreamingInsanity
  Creating multiple lists from file without long for loop Curtnos 2 4,447 Jan-28-2018, 09:11 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020