如何在python中迭代另一个列表中的列表

2024-05-19 00:40:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个43个对象的列表,然后每个对象包括75个点。这75个点中的每一个都显示了一天中的一个特定时间,我想从这43个物体中的每一个得到精确时间的标准偏差。我读到应该使用嵌套for循环,但它显示了一个零矩阵。有人能帮我吗

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')

因此,基本上我想要的是对j = 0到75重复下面的循环,但它不起作用

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

因此,如果有人感兴趣,我会找到它,下面的代码可以工作:

#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)

Tags: oftheinforplotnprangesd
2条回答

如果您有一个由全部为75个元素数组的元素组成的列表,则可以将该列表转换为适当的数组,并将标准偏差操作矢量化:

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

如果需要每天所有时间的标准偏差,请使用axis=1,如果需要43天所有测量值的标准偏差,请使用axis=None

您可以通过以相同的方式计算平均值来简化绘图:

my1 = y1.mean(0)
...

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

您正在订阅

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

但是i[j]没有意义,因为i是一个数字0,1,2,…,你应该输入

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

为了访问列表中的列表元素

相关问题 更多 >

    热门问题