如果列表的值大于某个特定值,则更改它们

我正在从文本文件中读取列表,并采用此列表的标准偏差,所以我想知道如何使值偏离均值超出一个标准差,而仅用作偏离均值的一个标准偏差。这是我正在使用的代码的一部分:


a=np.genfromtxt('meanvals2.txt').T[1]

b=np.std(a)

c=np.mean(a)

ok=(a>(c-b))*(a<(c+b)) # within 1st deviation

h=a[ok]

print h

此代码仅删除一个标准偏差之外的所有值。我将如何更改它,以使这些删除的值的上限为平均值的1个标准偏差,但保留在数据集中?


例如,如果我的清单是[1,2,3,4,5,20],则标准偏差为7.08,平均值为5.88。因此,远离平均值的一个标准偏差是12.96或-1.2,因此当前我的代码将排除此范围之外的任何数字,因此列表将为[1,2,3,4,5],但我希望列表实际读取[ 1,2,3,4,5,12.96]。我该怎么做


翻过高山走不出你
浏览 167回答 1
1回答

海绵宝宝撒

我想我可以分两个步骤进行操作:a = np.genfromtxt('meanvals2.txt').T[1]&nbsp;b = np.std(a)c = np.mean(a)#step 1, values lower than 1 std from meanok = a > (c - b)a[~ok] = c - b#step 2, values higher than 1 std from meanok = a < (c + b)a[~ok] = c + bprint a当然,如果您真的想要一个单独的数组h,可以先做h = a.copy(),然后再使用h代替a。以您的数据为例:>>> a = np.array([1,2,3,4,5,20],dtype=np.float32)>>> b = np.std(a)>>> c = np.mean(a)>>> print b6.46572151487>>> print c5.83333333333>>> ok = a > (c - b)>>> a[~ok] = c - b>>> ok = a < (c + b)>>> a[~ok] = c + b>>> print a[&nbsp; 1.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;12.2990551]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python