7

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?

8
  • I simply want a one column vector with 1000 rows as I am trying to subtract two column vectors Commented Mar 27, 2013 at 20:16
  • I think (1000,) is the same as (1000,1) Commented Mar 27, 2013 at 20:19
  • 1
    @MattDMo: they're sometimes interchangeable because of how numpy broadcasting works, but they're not quite the same thing. Commented Mar 27, 2013 at 20:20
  • You can see that if you just enter m[:,0] (prepare for a bit of scrolling, though :) Commented Mar 27, 2013 at 20:21
  • 2
    @MattDMo: well, the two objects have different dimensionality, for one. For a good broadcasting explanation you can read this tutorial. Commented Mar 27, 2013 at 20:27

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just to note, using m[:,[0]] is subtly different since it triggers fancy indexing, which means the result is not a view.
@seberg: true enough. I'm fortunate in that I seldom have to worry, either on memory or performance fronts, and so I've probably grown a little sloppy..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.