Home > Mobile >  Numpy: Boolean operation on np.array passed into function
Numpy: Boolean operation on np.array passed into function

Time:11-06

Numpy allows to pass a numpy.array as argument into a function and evaluate the function for every element of the array.:

def f(n):
    return n**2

arr = np.array([1,2,3])
f(arr)

outputs:

>>>[1 4 9]

This works fine, as long as f(n)doesn't perform boolean operations on n like this:

def f(n):
    if n%2 == 0:
        print(n)

The above code throws following exception: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This makes sense since the debugger showed, that the function f(n) received the entire numpy.arrayas input. Now, I'm looking for a way to change the code behaviour, so that I can perform boolean operations on the inputs. Is this possible while passing the entire numpy.array, or do I have to call the function by manually iterating over each element of the array?

---Edit:---

def get_far_field_directivity(k,a,theta):
    temp = k*a*np.sin(theta)
    if temp == 0: return 1
    else: return (2*sp.jn(1,(temp)))/(temp)

The function returns to other functions, which have to use its value on further calculation which is why the indexing approach by @Chrysophylaxs won't work.

CodePudding user response:

Your second example step by step with input np.array([1, 2, 3, 4, 5]):

  • First n%2 is executed, which returns np.array([1, 0, 1, 0, 1]), which is the elementwise modulo 2.
  • Next, the resulting array is elementwise compared to 0, which results in: np.array([False, True, False, True, False]).
  • Finally, this array is checked for truthyness in the if statement. That is where the problem occurs, because the array contains multiple elements, and numpy can't be sure whether you intend this to be True or False.

I suspect that instead you want to print all of the values in the input array whose modulo 2 equals 0. If that is the case, you can do that by filtering those out by indexing using the boolean array:

def f(n):
    evens = n[ n%2 == 0 ]
    print(evens)
Input:   f(np.array([1, 2, 3, 4, 5]))
Output:  array([2, 4])

CodePudding user response:

do you want to try something like this? https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html

import numpy as np

arr = np.array([1,2,3])

def f(n):
    if n%2 == 0:
        print(n)
    return n**2

vfunc = np.vectorize(f)      
vfunc(arr)          

outputs:

2
array([1, 4, 9])

whereas this

f(arr)     

outputs:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
  • Related