Make a NAN when the denominator is zero in the division between python arrays

Asked 2 years ago, Updated 2 years ago, 14 views

In the Python expression PER = EndPrice / EPS

EndPrice and EPS are two-dimensional arrays respectively

There are cases where the EPS is zero, so there is no error.

If the EPS is 0, I want to return the NAN value.

How do I code it?

python

2022-09-20 21:48

2 Answers

PER = float('nan') if EPS == 0 else EndPrise / EPS


2022-09-20 21:48

Looks like it's dealing with a numpy array. In this case, the following code is possible.

>>> a = np.array([1,2,3])
>>> b = np.array([1,4,0])
>>> a/b

Warning (from warnings module):
  File "<pyshell#21>", line 1
RuntimeWarning: divide by zero encountered in true_divide
array([1. , 0.5, inf])

>>> c = a/b
>>> c
array([1. , 0.5, inf])
>>> c[c==np.inf]
array([inf])
>>> c[c==np.inf] = np.nan
>>> c
array([1. , 0.5, nan])


2022-09-20 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.