Python array form

Suppose I create a two-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 I want. How can I force m[:,0] to an array (1000,1) ?

+6
source share
1 answer

Selecting the 0th column, in particular, as you noticed, you will reduce the dimension:

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

You have many options to return a 5x1 object. You can index using a list rather than an integer:

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

You can query "all columns, but not including 1":

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

Or you can use None (or np.newaxis ), which is a common trick for expanding sizes:

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

Finally, you can change the form:

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

but I would use one of the other methods for such a case.

+7
source

All Articles