1

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?

Bill Wan
  • 13
  • 3
  • I think you meant to do `f(active_N)` –  Jan 17 '23 at 04:41
  • Instead of vectorizing a function, you might consider this: https://stackoverflow.com/questions/70014001/make-elements-with-value-division-by-zero-equal-to-zero-in-a-2d-numpy-array – Mark Jan 17 '23 at 04:44
  • yeah I made a typo, it should be f(active_N) – Bill Wan Jan 18 '23 at 19:48

1 Answers1

0

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       ])
mozway
  • 194,879
  • 13
  • 39
  • 75