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?
Access the ith column of a Numpy array using transposeTranspose of the given array using the . T property and pass the index as a slicing index to print the array.
Select a single element from 2D Numpy Array by index We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.
In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix. Return: The number of rows and columns.
In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to the given conditions. Whenever we need to perform analysis, slicing plays an important role.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With