0
np.array([3, 2, 3]).T == np.array([[3],[2],[1]])

outputs:

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

Why isn't this equal and what does this output mean?

3
  • 1
    These arrays have a different number of dimensions, so comparing them for equality will create a broadcasting operation. Commented Feb 8, 2022 at 22:32
  • NumPy is an n-dimensional array library, not a matrix library. A NumPy transpose reverses the order of all dimensions an array actually has; if an array is not already 2D, it will not force the array to be 2D. Commented Feb 8, 2022 at 22:36
  • Did you look at np.array([3, 2, 3]).T? Commented Feb 9, 2022 at 1:28

1 Answer 1

2

So you have two arrays: np.array([3, 2, 3]).T (which is identical to the non-tranposed version: np.array([3, 2, 3])), and np.array([[3],[2],[1]]). Let's look at each one:

>>> a = np.array([3, 2, 3])
>>> a
array([3, 2, 3])

>>> b = np.array([[3],[2],[1]])
>>> b
array([[3],
       [2],
       [1]])

Note how the first (a) is 1D, while the second (b) is 2D. Since they have different dimensions, trying to compare them will do what's called "numpy broadcasting", and it's a really cool feature.

To break it down:

>>> a == b
array([[ True, False,  True],
       [False,  True, False],
       [False, False, False]])

Basically what the does, is for every item E in b, it checks if all the items in a are equal to E. To prove that:

>>> a == b[0]
array([ True, False,  True])

>>> a == b[1]
array([False,  True, False])

>>> a == b[2]
array([False, False, False])

Notice how the above arrays are identical to the whole array made by a == b. That's because a == b is a short, efficient form of doing the above.

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.