Accessing a NumPy-based array by a specific Column index can be achieved by indexing. NumPy follows standard 0-based indexing in Python.
Example:
Given array: 1 13 6 9 4 7 19 16 2 Input: print(NumPy_array_name[ :,2]) Output: [6 7 2] Explanation: printing 3rd column
Access ith column of a 2D Numpy Array in Python
Printing 1st row and 2nd column.
For column : numpy_Array_name[ : ,column] For row : numpy_Array_name[ row, : ]
import numpy as np
array = [[ 1 , 13 , 6 ], [ 9 , 4 , 7 ], [ 19 , 16 , 2 ]]
# defining array arr = np.array(array)
print ( 'printing 0th row' )
print (arr[ 0 , :])
print ( 'printing 2nd column' )
print (arr[:, 2 ])
# multiple columns or rows can be selected as well print ( 'selecting 0th and 1st row simultaneously' )
print (arr[:,[ 0 , 1 ]])
|
Output :
printing 0th row [ 1 13 6] printing 2nd column [6 7 2] selecting 0th and 1st row simultaneously [[ 1 13] [ 9 4] [19 16]]
Access the ith column of a Numpy array using transpose
Transpose of the given array using the .T property and pass the index as a slicing index to print the array.
import numpy as np
arr = np.array([[ 1 , 13 , 6 ], [ 9 , 4 , 7 ], [ 19 , 16 , 2 ]])
# Access the ith column of a 2D NumPy array column_i = arr.T[ 2 ]
#printing the column print (column_i)
|
Output:
[6 7 2]
Access the ith column of a Numpy array using list comprehension
Here, we access the ith element of the row and append it to a list using the list comprehension and printed the col.
import numpy as np
arr = np.array([[ 1 , 13 , 6 ], [ 9 , 4 , 7 ], [ 19 , 16 , 2 ]])
# Access the ith column of a 2D NumPy array col = [row[ 1 ] for row in arr]
# printing the column print (col)
|
Output:
[13, 4, 16]
Access the ith column of a Numpy array using Ellipsis
Pass the ith index along with the ellipsis to print the returned array column.
For column : numpy_Array_name[...,column] For row : numpy_Array_name[row,...] where '...' represents no of elements in the given row or column
Note: This is not a very practical method but one must know as much as one can.
import numpy as np
# defining array array = [[ 1 , 13 , 6 ], [ 9 , 4 , 7 ], [ 19 , 16 , 2 ]]
# converting to numpy array arr = np.array(array)
print ( 'selecting 0th column' )
print (arr[..., 0 ])
print ( 'selecting 1st row' )
print (arr[ 1 , ...])
|
Output:
selecting 0th column [ 1 9 19] selecting 1st row [9 4 7]