2

Want to select the data between 1 and 4, and convert others as np.nan But what's is the soluton?

import numpy as np
data = np.array([1,2,3,4,5])
selected = np.where(1<data<4, data, np.nan)
print (selected)

Traceback (most recent call last):
  File "C:/Users/fe/Desktop/t.py", line 3, in <module>
    selected = np.where(1<data<4, data, np.nan)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1 Answer 1

4

You are very close, you just need a different way to select the relevant indices in data. Try:

>>> selected = np.where((data < 4) & (data > 1), data, np.nan)
>>> selected
array([ nan,   2.,   3.,  nan,  nan])

(data < 4) & (data > 1) finds the indices of the data that are BOTH < 4 and >1.

Sign up to request clarification or add additional context in comments.

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.