Shape of array python

numpy, python

Solution

By selecting the 0th column in particular, as you've noticed, you reduce the dimensionality:

>>> m = np.random.normal(0, 1, size=(5, 2))
>>> m[:,0].shape
(5,)

You have a lot of options to get a 5x1 object back out. You can index using a list, rather than an integer:

>>> m[:, [0]].shape
(5, 1)

You can ask for "all the columns up to but not including 1":

>>> m[:,:1].shape
(5, 1)

Or you can use `None` (or `np.newaxis`), which is a general trick to extend the dimensions:

>>> m[:,0,None].shape
(5, 1)
>>> m[:,0][:,None].shape
(5, 1)
>>> m[:,0, None, None].shape
(5, 1, 1)

Finally, you can reshape:

>>> m[:,0].reshape(5,1).shape
(5, 1)

but I'd use one of the other methods for a case like this.

Problem

Suppose I create a 2 dimensional array ``` m = np.random.normal(0, 1, size=(1000, 2)) q = np.zeros(shape=(1000,1)) print m[:,0] -q ``` When I take `m[:,0].shape` I get `(1000,)` as opposed to `(1000,1)` which is what I want. How do I coerce `m[:,0]` to a `(1000,1)` array?

Original source