python正态分布
我有一个数字列表,带有这些数字的样本平均值和SD。现在我正试图找出平均值+-SD,平均值+-2SD和平均值+-3SD之外的数字。 例如,在mean+-SD部分,我编写了如下代码:python正态分布,python,python-3.x,Python,Python 3.x,我有一个数字列表,带有这些数字的样本平均值和SD。现在我正试图找出平均值+-SD,平均值+-2SD和平均值+-3SD之外的数字。 例如,在mean+-SD部分,我编写了如下代码: ND1 = [np.mean(l)+np.std(l,ddof=1)] ND2 = [np.mean(l)-np.std(l,ddof=1)] m=sorted(l) print(m) ND68 = [] if ND2 > m and m< ND1: ND68.append(m&l
ND1 = [np.mean(l)+np.std(l,ddof=1)]
ND2 = [np.mean(l)-np.std(l,ddof=1)]
m=sorted(l)
print(m)
ND68 = []
if ND2 > m and m< ND1:
ND68.append(m<ND2 and m>ND1)
print (ND68)
ND1=[np.平均值(l)+np.标准值(l,ddof=1]
ND2=[np.平均值(l)-np.标准值(l,ddof=1]
m=已排序(l)
打印(m)
ND68=[]
如果ND2>m且m
我的问题是:
1.可以通过列表和排列来计算数字。如果是,我做错了哪一部分。或者我可以用一些软件包来解决这个问题。这可能会有所帮助。我们将使用
numpy
获取您要查找的值。在我的示例中,我创建了一个正态分布数组,然后使用布尔切片返回+/-1、2或3标准偏差之外的元素
import numpy as np
# create a random normally distributed integer array
my_array = np.random.normal(loc=30, scale=10, size=100).astype(int)
# find the mean and standard dev
my_mean = my_array.mean()
my_std = my_array.std()
# find numbers outside of 1, 2, and 3 standard dev
# the portion inside the square brackets returns an
# array of True and False values. Slicing my_array
# with the boolean array return only the values that
# are True
out_std_1 = my_array[np.abs(my_array-my_mean) > my_std]
out_std_2 = my_array[np.abs(my_array-my_mean) > 2*my_std]
out_std_3 = my_array[np.abs(my_array-my_mean) > 3*my_std]
你在那里走对了。您知道列表的平均值和标准偏差
l
,尽管我将把它称为不那么模棱两可的东西,比如说,samplePopulation
因为您希望对几个标准偏差间隔执行此操作,所以我建议制作一个小函数。您可以多次调用它,而无需做太多额外的工作。另外,我将使用a,它只是一行中的for
循环
import numpy as np
def filter_by_n_std_devs(samplePopulation, numStdDevs):
# you mostly got this part right, no need to put them in lists though
mean = np.mean(samplePopulation) # no brackets needed here
std = np.std(samplePopulation) # or here
band = numStdDevs * std
# this is the list comprehension
filteredPop = [x for x in samplePopulation if x < mean - band or x > mean + band]
return filteredPop
# now call your function with however many std devs you want
filteredPopulation = filter_by_n_std_devs(samplePopulation, 1)
print(filteredPopulation)
因此,总结一下:
- 你不需要根据你的平均值和标准差计算结果来制作一个列表对象
- 函数调用允许您插入
和任意数量的标准偏差,而无需进入并手动更改值samplePopulation
- 列表理解是循环的一行,或多或少,你甚至可以在里面做你想要的过滤李>
# remember that you provide the variable samplePopulation
# the above list comprehension
filteredPop = [x for x in samplePopulation if x < mean - band or x > mean + band]
# is equivalent to this:
filteredPop = []
for num in samplePopulation:
if x < mean - band or x > mean + band:
filteredPop.append(num)