Adrian Keister
Adrian Keister

Reputation: 1025

Slicing array returns strange shape

Suppose I do the following in Ipython:

import numpy as np
test = np.zeros([3,2])
test
test.shape
test[:,0]
test[:,0].shape

The results will be:

array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])
(3,2)
array([ 0.,  0.,  0.])
(3,)

Why is the last result here not (3,1)? I have a work-around: The reshape command, but that seems silly.

Upvotes: 1

Views: 538

Answers (2)

Daniel F
Daniel F

Reputation: 14399

If you have only one coordinate in a given dimension but want to keep that dimension, wrap it in an array or list

test[:,[0]].shape
Out: (3, 1)

Upvotes: 1

MSeifert
MSeifert

Reputation: 152627

I use a different array for visualization:

>>> import numpy as np
>>> test = np.arange(6).reshape(3, 2)
>>> test
array([[0, 1],
       [2, 3],
       [4, 5]])

Slicing like this:

>>> test[:,0]
array([0, 2, 4])

tells NumPy to keep the first dimension but only take the first element of the second dimension. By definition this will reduce the number of dimensions by 1.

Just like:

>>> test[0, 0]
0

would take the first element in the first dimension and the first element of the second dimension. Thus reducing the number of dimensions by 2.

In case you wanted to get the first column as actual column (not changing the number of dimensions) you need to use slicing:

>>> test[:, 0:1]  # remember that the stop is exlusive so this will get the first column only
array([[0],
       [2],
       [4]])

or similarly

>>> test[:, 1:2]  # for the second column
array([[1],
       [3],
       [5]])

>>> test[0:1, :]  # first row
array([[0, 1]])

Upvotes: 2

Related Questions