In python, I'm trying to inverse a numpy vector except for these elements with zero values.
- I used vectorize function, but always got a wrong answer when the first element is zero, (the code works well when zeros are not in the first position ).
active_N=np.array([0,1,3,5])
f=np.vectorize(lambda x:x if x==0 else 1./x)
active_N_inverse=f(active_N_inverse)
Run the code then I get
array([0, 0, 0, 0])
What was wrong with the codes above? Is there any other method to solve this problem with high efficiency?
CodePudding user response:
Use np.divide
with a where
clause:
np.divide(1, active_N, where=active_N!=0)
Optionally combined with round
:
np.divide(1, active_N, where=active_N!=0).round(100)
Output:
array([0. , 1. , 0.33333333, 0.2 ])