'What is the correct way to access the columns in NumPy?

I cannot figure out the following problem:

Elements that were placed at the corners of an 4X3 array are selected. The row indices of the selected items are [0, 0] and [3, 3] whereas the column indices are [0, 2] and [0, 2]. My code executes correctly but I want to know how the columns are represented. And what is the correct way to access the columns in NumPy?

import numpy as np 
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]]) 

print 'Our array is:' 
print x 
print '\n' 

rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]]) 
y = x[rows,cols] 

print 'The corner elements of this array are:' 
print y


Solution 1:[1]

I don't quite understand what you want. But maybe this will help

In [79]: x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]]) 

print display of x:

In [80]: x
Out[80]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

Corner selection with advanced indexing:

In [81]: rows = np.array([[0,0],[3,3]])
    ...: cols = np.array([[0,2],[0,2]]) 
In [83]: x[rows, cols]
Out[83]: 
array([[ 0,  2],
       [ 9, 11]])

A view (see docs) of a column (last):

In [85]: x[:, 2]
Out[85]: array([ 2,  5,  8, 11])

A view of a row:

In [86]: x[2, :]
Out[86]: array([6, 7, 8])

Solution 2:[2]

import numpy as np 
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]]) 
   
print('Our array is:' ) 
print (x) 
print ('\n' )

rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]]) 
y = x[rows,cols] # ([0,0],[3,3],[0,2],[0,2]) = (R,R,C,C) =Final Ans (0,0),(0,2),(3,0),(3,2)
   
print ('The corner elements of this array are:' )
print (y)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hpaulj
Solution 2 Suraj Rao