2

I am trying to understand how slicing works in numpy.

A = np.array([0, 1])
B = np.array([0, 1])
B = B[:, None]

print(A[None, :] == B[:, None]) 

The code in python gives

[[[ True False]]

 [[False  True]]]

Would someone be able to help explain why that is so?

2 Answers 2

1

Because B = B[:, None] changes the array to 2d:

A = np.array([0, 1])
B = np.array([0, 1])
C = B[:, None]
print(B, C, sep='\n')

Output:

[0 1]
[[0]
 [1]]

They become different.

Also:

>>> A[:, None]
array([[0],
       [1]])
>>> A[None, :]
array([[0, 1]])
>>> 

Aren't the same.

[:, None] makes it into a shape of (2, 1), where [None, :] makes it into (1, 2).

That's the difference, one transposes columns-wise, and one transposes row-wise.

Also for checking equality it becomes checking from A[:, None], with:

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

And for A[None, :] it checks for:

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

So the first list row would be [True, False], because 0 == 0 but 0 != 1. And for the second row it would be [False, True], because 1 != 0 but 1 == 1.

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

Comments

1

when you write B[:, None] you change B to shape=(2,1) and each element place in one row and when you write A[None, :] you change A to shape=(1,2) and each element place in one column see:

B = np.array([0, 1])
B = B[:, None]
#[[0]
# [1]]
A = A[None , :]
# array([[0, 1]])

then:

[B[0][0] == A[0][0] , B[0][0] == A[0][1]]
# True , False
[B[1][0] == A[0][0] , B[1][0] == A[0][1]]
# Fale  True

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.