[Numpy-discussion] Extracting individual columns in Numpy

Nathaniel Smith njs at pobox.com
Thu Oct 9 01:52:45 EDT 2014

On Thu, Oct 9, 2014 at 6:42 AM, suchith <suchithjn22 at 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


Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh

More information about the NumPy-Discussion mailing list