Search code examples
pythonarraysnumpymasking

How do I take the reciprocal of all non-zero entries in a numpy array


I am trying to take the reciprocal of every non zero value in a numpy array but am messing something up. Suppose:

norm = np.arange(0,11)

I would like the np.array that would be (maintaining the zeros in place)

[ 0, 1, 0.5 , 0.33, 0.25, 0.2 , 0.17, 0.14, 0.12, 0.11, 0.1] 

If I set

mask = norm !=0 

and I try

1/norm[mask]

I receive the expected result of

[1, 0.5 , 0.33, 0.25, 0.2 , 0.17, 0.14, 0.12, 0.11, 0.1] 

However I'm trying to understand why is it that when I try the following assignment

norm[mask] = 1/norm[mask]    

i get the following numpy array.

[0,1,0,0,0,0,0,0,0,0,0]

any ideas on why this is or how to achieve the desired np.array?


Solution

  • Are you sure you didn't accidentally change the value of norm.

    Both

    mask = norm != 0
    norm[mask] = 1 / norm[mask]
    

    and

    norm[norm != 0] = 1 / norm[norm != 0]
    

    both do exactly what you want them to do. I also tried it using mask on the left side and norm != 0 on the right side like you do above (why?) and it works fine.

    EDIT BY FY: I misread the example. I thought original poster was starting with [0, .5, .333, .25] rather than with [0, 1, 2, 3, 4]. Poster is accidentally creating an int64 array rather than a floating point array, and everything is rounding down to zero. Change it to np.arange(0., 11.)