Home > OS >  operating on array with condition
operating on array with condition

Time:01-15

Consider the following code,

import numpy as np

xx = np.asarray([1,0,1])

def ff(x):
    return np.sin(x)/x

# this throws an error because of division by zero
# C:\Users\User\AppData\Local\Temp/ipykernel_2272/525615690.py:4: 
# RuntimeWarning: invalid value encountered in true_divide
# return np.sin(x)/x

yy = ff(xx)

# to avoid the error, I did the following
def ff_smart(x):
    if (x==0):
        # because sin(x)/x = 1 as x->0
        return 1
    else:
        return np.sin(x)/x

# but then I cannot do
# yy_smart = ff_smart(xx)
# because of ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# I therefore have to do:

*yy_smart, = map(ff_smart,xx)
yy_smart = np.asarray(yy_smart)

Is there a way (some numpy magic) to write ff_smart such that I can call it without using map and ff_smart remains operable on scalars (non numpy arrays). I'd like to avoid type-checking in ff_smart.

CodePudding user response:

For conditional operations as you describe numpy has the numpy where function.

You can do

np.where(x==0, 1, np.sin(x)/x)

CodePudding user response:

you can do:

yy = [np.sin(x)/x if x != 0 else 1 for x in xx]
  •  Tags:  
  • Related