简体   繁体   中英

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?

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.)

another option is using numpy.reciprocal as documented here with a parameter where as followed:

import numpy as np
data = np.reciprocal(data,where= data!=0)

example:

In[1]: data = np.array([2.0,4.0,0.0])
in[2]: np.reciprocal(data,where=data!=0)
Out[9]: array([0.5 , 0.25, 0.  ])

notice that this function is not intended to work with ints , therefore the initialized values are with the .0 suffix. if you're not sure of the type, you can always use data.astype(float64)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM