Mo Raz
Mo Raz

Reputation: 3

How to iterate a list within another list in python

I have a list of 43 objects and then each object includes 75 points. Each of those 75 points shows a specific time of the day and I want to get the standard deviation of that exact time from each of those 43 objects. I read that I should use a nested for loop but it shows a matrix of zeros. Can anyone help me?

y1 = [
    a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
    a11, a12, a13, a14, a15, a16, a17, a18, a19, a20,
    a21, a22, a23, a24, a25, a26, a27, a28, a29, a30,
    a31, a32, a33, a34, a35, a36, a37, a38, a39, a40,
    a41, a42, a43
]

#an example of what 'a' is
a1 = np.array(df1['Level'][33:108])
a2 = np.array(df1['Mlevel'][105:180])

#get the standard deviation
SD = []
for i in range(43):
    for j in range(75):
        SD.append(np.std(y1[i[j]]))

#plot the standard deviation with mean
for i in range(43):
    axs[0].plot(x1, mean_y1 + SD, color='lightblue')
    axs[0].plot(x1, mean_y1 - SD, color='lightblue')

So basically what I want is to repeat the loop below for j = 0 to 75 but it does not work.

c0 = []
for i in range(43):
    c0.append((y1[i][0]))
print(np.std(c0))

So in case anyone is interested I figured it out and the code below works:

#create a list of all the elements (c)
c = []    
for j in range(75):
     for i in range(43): 
         c.append((y1[i][j]))
     
     
#print(c) 

#Get the standard deviation of every 43 points    
start = 0       # First to consider
stop = 3225     # the length of the list c
interval = 43   # chunk size

SD = []
for i in range(start, stop, interval):
    SD.append(np.std(c[i:(i + interval)]))
    
print(SD)

Upvotes: 0

Views: 128

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114320

If you have a list consisting of elements that are all 75-element arrays, you can convert the list into a proper array and vectorize the standard deviation operation:

y1 = np.array(y1)
sd = np.std(y1, axis=0)

Use axis=1 if you want standard deviation across all the times in each day, and axis=None for the standard deviation of all the measurements across all 43 days.

You can likely simplify the plots by computing the mean in the same way:

my1 = y1.mean(0)
...

    axs[0].plot(x1, my1 + sd, color='lightblue')
    axs[0].plot(x1, my1 - sd, color='lightblue')

Upvotes: 0

DovaX
DovaX

Reputation: 1026

You are subscripting

SD.append(np.std(y1[i[j]])) 

but i[j] does not make sense, because i is a number 0,1,2,..., you should rather type

SD.append(np.std(y1[i][j]))

in order to access an element of a list in a list

Upvotes: 1

Related Questions