0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

you don't have to create zeros array , comparing using np.where( b > 0 , b , 0) is enough
Yes I just noticed that and editted. Thanks for the improvment.
@NaderHisham I'm keeping this sample to illustrate the fact that np.where works with 2 arrays.
1

Use array masking:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.