0

Is there any way to convert an array to a binary array such that any element that exists within a defined list is 1, and any element not in the list is 0?

For example, if I define a NumPy array as so:

a = np.array([[23,43,1],[43,5,0],[5,0,0]])

and a list as so:

l = [5,43]

I want a function that converts the array to/creates this:

array([[0, 1, 0],
       [1, 1, 0],
       [1, 0, 0]])

I have already tried np.where(a in l, 1, 0), and it gives me this error:

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

1 Answer 1

1

Check out https://numpy.org/doc/stable/reference/generated/numpy.isin.html

arr=np.array([[23,43,1],[43,5,0],[5,0,0]])
l = [5,43]
np.isin(arr, l).astype(int)
#array([[0, 1, 0],
#       [1, 1, 0],
#       [1, 0, 0]])
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.