4

I have a numpy array

a = numpy.array([1,2,3,0])

I would like to do something like

a == numpy.array([0,1,2,3])

and get

[[False, True,   False, False],
 [False, False,  True,  False],
 [False, False,  False, True ],
 [True,  False,  False, False]]

In other words, I want the ith column to show whether each element of a is equal to i. This feels like the kind of thing that numpy might make easy. Any ideas?

4 Answers 4

7

The key concept to use here is broadcasting.

a = numpy.array([1,2,3,0])
b = numpy.array([0,1,2,3])
a[..., None] == b[None, ...]

The result:

>>> a[..., None] == b[None, ...]
array([[False,  True, False, False],
       [False, False,  True, False],
       [False, False, False,  True],
       [ True, False, False, False]], dtype=bool)

Understanding how to use broadcasting will greatly improve your NumPy code. You can read about it here:

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

Comments

1

You can reshape to vector and covector and compare:

>>> a = numpy.array([1,2,3,0])
>>> b = numpy.array([0,1,2,3])
>>> a.reshape(-1,1) == b.reshape(1,-1)
array([[False,  True, False, False],
       [False, False,  True, False],
       [False, False, False,  True],
       [ True, False, False, False]], dtype=bool)

Comments

1

The above is one way of doing it. Another possible way (though I'm still not convinced there isn't a better way) is:

import numpy as np
a = np.array([[1, 2, 3, 0]]).T
b = np.array([[0, 1, 2, 3]])
a == b
array([[False,  True, False, False],
   [False, False,  True, False],
   [False, False, False,  True],
   [ True, False, False, False]], dtype=bool)

I think you just need to make sure one is a column vector and one is a row vector and it will do comparison for you.

3 Comments

This is the same as the above answer. Beat me haha, I was trying to figure out format. How do I get the arrows to show up?
If by "arrows" you mean the REPL's >>> you can copy them from your interpreter.
exactly what I meant thank you. I also learned a new term. Thanks again.
0

You can use a list comprehension to iterate through each index of a and compare that value to b:

>>> import numpy as np
>>> a = np.array([1,2,3,0])
>>> b = np.array([0,1,2,3])
>>> ans = [ list(a[i] == b) for i in range(len(a)) ]
>>> ans
[[False,  True, False, False],
 [False, False,  True, False],
 [False, False, False,  True],
 [ True, False, False, False]]

I made the output match your example by creating a list of lists, but you could just as easily make your answer a Numpy array.

1 Comment

Definitely works. I was wondering if there was something more built in to numpy. This feels like the kind of thing that might be part of the library.

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.