Wednesday, May 27, 2020

NumPy Array Indexing

NumPy Array Indexing


Array indexing

The basic behavior of arrays is that they can be accessed using the indexes. We can access an array item by using its index position. The index position starts at 0, so the first element has index 0, and the second has index 1, the third has position 2, and so on. Awareness of the fundamentals of array indexing is very useful for analyzing and retrieving the arrays. NumPy provides multiple ways to do array indexing.

For example,

import numpy as np
nums = np.array([7,23,12,51])
print(nums[0]) #First item 7
print(nums[3]) #Last item 51

2-D Arrays indexing 

A 2-D array can be easily accessed by using the comma-separated dimension and index position of the item. For example,

import numpy as np
nums = np.array([[7,23,12,51],[8,9,23,5],[11,4,3,2]])
print(nums)
print(nums[1,2]) 
print(nums[2,3])


#Output
[[ 7 23 12 51]
 [ 8  9 23  5]
 [11  4  3  2]]
23
2

3-D array indexing


Accessing a 3-D array is similar to accessing the 2-D array except a dimension is also added to the comma-separated list.
 
import numpy as np
nums = np.array([[[7,23,12,51],[8,9,23,5]],[[11,4,3,2],[23,12,45,16]]])
print(nums)
print(nums[1,1,0]) 
print(nums[0,1,3])
print(nums[1,0,2])

#Output
[[[ 7 23 12 51]
  [ 8  9 23  5]]

 [[11  4  3  2]
  [23 12 45 16]]]
23
5
3


Negative indexing 


As we can use negative indexing in Python, it is also possible to use negative indexes with ndarray object. The negative index of the last item in the array is  -1, second last -2, and so on. For example

import numpy as np
colors=np.array(['RED','BLUE','GREEN','GREEN','CYAN']);
print(colors[-1])
print(colors[-2])
print(colors[-3])
print(colors[-4])

#Output
CYAN
GREEN
GREEN
BLUE

similarly, we can access a multi-dimensional array,

import numpy as np

nums = np.array([[23,11,51],[9,23,5],[4,3,2],[12,45,16]])
print(nums)
print(nums[1,-1]) #last item from second row 5
print(nums[0,-2]) # second last item from first row 11
print(nums[-1,-3]) #last third item from last row  12

#output
[[23 11 51]
 [ 9 23  5]
 [ 4  3  2]
 [12 45 16]]
5
11
12

Setting the item


We can also set the item value using indexes.

import numpy as np
nums = np.array([[23,11,51],[9,23,5],[4,3,2],[12,45,16]])
nums[1,2]=34
nums[3,1]=50
print(nums)

#Output
[[23 11 51]
 [ 9 23 34]
 [ 4  3  2]
 [12 50 16]]
import numpy as np
nums = np.array([12,1,7,43],int)
nums[2]=34.7 # .7 will be truncated
print(nums)

#Output
[12  1 34 43]