On Thu, Oct 9, 2014 at 6:42 AM, suchith <suchithj...@gmail.com> wrote:
> How to extract individual columns from a numpy array?
> For example, consider this script
>
> import numpy as np
> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
> a[0][:]
> a[:][0]
>
> Now both a[:][0] and a[0][:] are outputting the same result, i.e
> np.array([1,2,3]). If I want to extract the array [[1],[4],[7]] then what
> should I do?

You want a[:, 0]. I'd recommend never writing expressions like a[0],
where you give just 1 index into a 2d array -- numpy interprets such a
thing as equivalent to a[0, :], so you should just write a[0, :] in
the first place, it'll be more explicit and less confusing. (This also
explains the problem you're having: a[:] is the same as a[:, :], i.e.,
it just returns all of 'a'. So a[:][0] is the same as a[0]. Similarly,
a[0][:] returns all of a[0].)

(The one time you might want to write something that looks like
a[foo], with no commas inside the [], is where 'foo' is a 2d boolean
mask.)

-n


-- 
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@scipy.org
http://mail.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to