scipy 使用python屏蔽mxn数组

qco9c6ql  于 2023-01-09  发布在  Python
关注(0)|答案(3)|浏览(130)

Hii我有一个mxn数组数据,我想用0和1值屏蔽它。如果存在0以外的值,我想使它成为1,而不是0,我想让它保持原样。如果我的值是这样的0.0000609409412,即在小数点后,如果4位或更多位是零,那么它应该是零而不是1

Input:
-2.21520694000000e-15   -1.18292704000000e-15   5.42940708000000e-15      
-2.40108895000000e-15    3.09784301000000e-15  -1.18292704000000e-14
 0                       0                      0
 1.50000000000000        2.100000000000000000   1.40000000000000000

output:
1                       1                   1
1                       1                   1
0                       0                   0
1                       1                   1
gojuced7

gojuced71#

编辑:根据你的评论更新了我的答案。
试试这个,简单的基于上限和下限的条件,使用OR |运算符,然后将类型转换为int。

lower_limit, upper_limit = -0.00001, 0.00001
masked = ((arr<lower_limit)|(arr>upper_limit)).astype('int')

#Testing it out
[str(j)+'-> masked to -> '+str(masked[i]) for i,j in enumerate(arr)]
['0.0-> masked to -> 0',
 '1.0-> masked to -> 1',
 '0.1-> masked to -> 1',
 '0.01-> masked to -> 1',
 '0.001-> masked to -> 1',
 '0.0001-> masked to -> 1',
 '1e-05-> masked to -> 0',
 '1e-06-> masked to -> 0',
 '1e-07-> masked to -> 0',
 '1e-08-> masked to -> 0']
lrl1mhuk

lrl1mhuk2#

试试这个:

array = np.array([
    [-2.21520694000000e-15, -1.18292704000000e-15, 5.42940708000000e-15],
    [-2.40108895000000e-15,   3.09784301000000e-15, -1.18292704000000e-14],
    [0                    ,  0                    , 0],
    [1.50000000000000     ,  2.100000000000000000 , 1.40000000000000000]
])
result = (array != 0).astype('int')
b4lqfgs4

b4lqfgs43#

使用numpy有很多不同的方法来实现这一点,例如类型转换:

# given arr is <np.ndarray: m, n> 
new_arr = arr.astype(bool).astype(int)

如果要过滤掉低于某个阈值的值,可以执行以下操作:

threshold = 0.0001
new_arr = (arr >= threshold).astype(int)

相关问题