首页 > 解决方案 > 使用 python 屏蔽 mxn 数组

问题描述

嗨,我有一个 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

标签: python-3.xpandasnumpyfor-loopscipy

解决方案


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

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

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

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

推荐阅读