djokovic
djokovic

Reputation: 43

Numpy array slicing using None and colon:

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?

Upvotes: 2

Views: 262

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

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

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

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.

Upvotes: 1

Related Questions