18

Possible Duplicate:
numpy: access an array by column

I have a numpy array (numpy is imported as np)

gona = np.array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

I can get the values of entire column of 1th row by gona[1][:].

array([4, 5, 6])

But if I try to get all values of a particular column of all rows (say I want values of 1st column in every row) I would try the gona[:][1]. But the result I get from this is same as before.

What can be the reason for this? How do I do such a thing in numpy?

1
  • 1
    no. I wanted know why both ways give same results too Commented Feb 1, 2013 at 17:39

3 Answers 3

40

You actually want to do this:

>>> a
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
>>> a[:,1]
array([ 2,  5,  8, 11])

a[:] just returns the entire array, so then a[:][1] is returning the second row of a. I think that's where your confusion arises.

See this section of the Tentative Numpy Tutorial for more information on indexing multidimensional arrays.

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

5 Comments

a[:][1] selects the second row
Oops. You're right. I've corrected that.
This did the job. Thank you
What does the comma mean?
The comma is the axis delimiter, so in this example, I'm selecting all elements along the first axis, and only the second element along the second axis.
9

There seems to be a slight confusion in terms of the positioning of the braces, gona[:][1] first selects everything from the array, and from that array then selects the second row. To select particular columns you put the indices within the same square brackets separated by a comma:

gona = np.array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

gona[1,:]
Out[21]: array([4, 5, 6])

gona[:,1]
Out[22]: array([ 2,  5,  8, 11])

gona[:,0]
Out[23]: array([ 1,  4,  7, 10])

you can also just select a range of rows for instance

gona[0:2,0] # only take the two first rows of the first column
Out[24]: array([2, 5])

1 Comment

thank you separately for selecting a range of rows code :)
1

Like this:

gona = numpy.array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

# List comprehension, just get each element in 'gona', and then get first element in that list
out = [x[0] for x in gona]

print out

Output:

>>> 
[1, 4, 7, 10]
>>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.