Reputation: 430
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
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