Marcin
Marcin

Reputation: 430

numPy logic function over an array

I'm trying to generate a vector [a(1), a(2),...a(100)] where a(i) is sin(i) if sin(i)>0, and 0 otherwise. What I came up with is creating a lambda expression and applying it through numpy.fromfunction, as such: np.fromfunction(lambda i, j: sin(j) if np.sin(j) > 0 else 0, (1, 100), dtype=int) , but this produces an error

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

How can I get around that? Thanks

Upvotes: 0

Views: 99

Answers (2)

P. Camilleri
P. Camilleri

Reputation: 13218

For your particular case, you can use np.maximum(np.sin(range(100)), np.zeros(100))

More generally use np.where() to create an array based on a comparison of 2 arrays:

b = np.sin(range(100))
c = np.zeros(100)
a = np.where(b > c, b, 0)

or, in your case,

b = np.sin(range(100))
a = np.where(b > 0, b, 0)

(no need to create c)

Edit: though where() allows for more complex allocations, it seems to be slower:

%timeit a = np.where(b > 0, b, 0)
100000 loops, best of 3: 2.15 µs per loop

%timeit b[b<0] = 0
100000 loops, best of 3: 1.11 µs per loop

Upvotes: 1

mtzl
mtzl

Reputation: 404

Use array masking:

a = np.arange(1, 101)
b = np.sin(a)
b[b<0] = 0

Upvotes: 1

Related Questions