Rol
Rol

Reputation: 209

Why is arr[:][np.newaxis].shape = (1, n) instead of (n, 1)?

The standard use of np.newaxis (or None) is within the index brackets. For example

arr = np.arange(4)
print(arr[:,None].shape)
print(arr[None,:].shape)

gives

(4,1)
(1,4)

But I recently saw someone using it as an index in a separate bracket, like so

arr = np.arange(4)
print(arr[:][None].shape)
print(arr[None][:].shape)

which gives

(1,4)
(1,4)

To my surprise, both results are the same, even though the newaxis was in the second index position in the first case. Why is arr[:][None].shape not (4,1)?

Upvotes: 1

Views: 408

Answers (1)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5945

In arr[:][np.newaxis] and arr[np.newaxis][:] the indexing is done sequentially, so arr2 = arr[:][np.newaxis] is equivalent to:

arr_temp = arr[:]
arr2 = arr_temp[np.newaxis]
del arr_temp

The same logic applies to ordering the indexing operators the other way round, for arr2 = arr[np.newaxis][:]:

arr_temp = arr[np.newaxis]
arr2 = arr_temp[:]
del arr_temp

Now, to quote https://numpy.org/doc/1.19/reference/arrays.indexing.html:

Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.

Since np.newaxis is at the first position (there is only one position) in the indexing selection tuple in both arr[np.newaxis] and arr_temp[np.newaxis], it will create the new dimension as the first dimension, and thus the resulting shape is (1, 4) in both cases.

Upvotes: 2

Related Questions