masking a mxn array using python

Question:

Hii i have a mxn array data and i want to mask it using 0 and 1 values.Where the values other than 0 is present i want to make it 1 and in place of 0 i want to leave it as it is.If my values are something like this 0.0000609409412 i.e. after decimal point if 4 digits or more are zero then it should be zero not 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
Asked By: manas

||

Answers:

There are many different ways to achieve this using numpy, e.g. type casting:

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

If you want to filter out values below a certain threshold, you can do something like this:

threshold = 0.0001
new_arr = (arr >= threshold).astype(int)
Answered By: NMme

Try this:

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')
Answered By: Code Different

EDIT: Updated my answer based on your comments.

Try this, simple upper and lower limit-based conditions with an OR | operator followed by type conversion to 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']
Answered By: Akshay Sehgal
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.