Python slice without dimension

Why slicing one row or column produces "dimensionless array"? For example:

import numpy as np
arr = np.zeros((10,10))
print arr.shape
# (10, 10)

But when I want only one column or row, I get

print arr[:,0].shape
# (10,)
print arr[0,:].shape
# (10,)

instead of

print arr[:,0].shape
# (10, 1)
print arr[0,:].shape
# (1, 10)

Upvotes: 2

Views: 869

Answers (1)

Anton Protopopov
Anton Protopopov

Reputation: 31682

For you example you getting np.arrays from 0 column and from 0 row which are numpy.array with 1 dimension. You could do a little trick with slicing like that:

In [103]: arr[:1,:].shape
Out[103]: (1, 10)

In [104]: arr[:,:1].shape
Out[104]: (10, 1)  

EDIT

From docs:

An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N - 1. If N = 1 then the returned object is an array scalar. These objects are explained in Scalars.

Upvotes: 1

Related Questions