如何在Python中为数组中的每个元素运行for循环?

时间:2018-04-06 17:17:46

标签: python arrays python-3.x for-loop

我有一个代码,它适用于高斯样本,加上100倍的噪声,然后找到样本的拟合stdv的标准偏差。我希望代码运行超过100个不同的噪声stdv值,并将结果保存在一个新的数组中。我的代码如下所示:

import numpy as np
from scipy.optimize import curve_fit

points = 100
noise_stdv1 = np.linspace(0.0, 0.1, points)
G_stdv = []
G_initial = [0.0, 1.0]
range1 = np.linspace(-5.0, 5.0, points)

def gaussian(x, mu, sigma):
    return np.exp(-(x - mu)**2 / (2*(sigma)**2))

for i in noise_stdv1:

   noise1 = [np.random.normal(0.0, 0.1, points) for i in range(points)]
   G_sample = [gaussian(range1, 0.0, 1.0) for i in range(points)]
   G_noise = [G_sample[i] + noise1[i] for i in range(points)]
   G_param1 = [curve_fit(gaussian, range1, G_noise[i], p0 = G_initial) for i in range(points)]
   G_param2, G_covar = map(list, zip(*G_param1))
   G_param_stdv = [i for _,i in G_param2]
   G_stdv.append(np.std(G_param_stdv))

其中G_stdv应该是for循环每次迭代的保存标准偏差。但是,当我运行代码时,G_stdv数组只包含来自noise_stdv1中最后一个元素的100个结果,而不是每个元素的一个结果。任何人都可以帮我解决如何让for循环为noise_stdv1中的每个元素正确运行一次?

0 个答案:

没有答案