inverse elements except for zero in a numpy vector

Question:

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)

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?

Asked By: Bill Wan

||

Answers:

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       ])
Answered By: mozway
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.