我有一个列表pct_change
。我需要在列表上计算std偏差而忽略零。我试过下面的代码,但它没有按预期工作。
import numpy as np
m = np.ma.masked_equal(pct_change, 0)
value = m.mask.std()
输入值:pct_change
0 0.00
1 0.00
2 0.00
3 18523.94
4 15501.94
5 14437.03
6 13402.43
7 18986.14
代码必须忽略3个零值,然后计算标准偏差。
答案 0 :(得分:2)
首先过滤不等于零的值:
>>> a
array([ 0. , 0. , 0. , 18523.94, 15501.94, 14437.03,
13402.43, 18986.14])
>>> a[a!=0].std()
2217.2329816471693
答案 1 :(得分:0)
一种方法是将zeros
转换为NaNs
,然后使用np.nanstd
忽略NaNs
进行标准差计算 -
np.nanstd(np.where(np.isclose(a,0), np.nan, a))
示例运行 -
In [296]: a
Out[296]: [0.0, 0.0, 0.0, 18523.94, 15501.94, 14437.03, 13402.43, 18986.14]
In [297]: np.nanstd(np.where(np.isclose(a,0), np.nan, a))
Out[297]: 2217.2329816471693
请注意,我们正在使用np.isclose(a,0)
因为我们在这里处理的是floating-pt
个数字,所以简单地与zeros
进行比较以检测float dtype数组中的数字并不是一个好主意。< / p>