/    /  NumPy – Advanced Indexing

NumPy – Advanced Indexing:

 Let us say x[obj] is an array which holds obj as the selection object. When the object is a non-tuple sequence object or a tuple with atleast one sequence object which is ndarray of type integer or Boolean.
Note: Advanced indexing always returns a copy of data but not view as like basic slicing.
Here, there are 2 types of advanced indexing.
1. Integer Array Indexing
2. Boolean Indexing
Integer Array Indexing:
Syntax:
result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, 
..., i_M], ..., ind_N[i_1, ..., i_M]]
Example:
 Below, we have created an array with integers.
>>> x=np.array([[1,2],[3,4],[5,6]])
Output:
>>> x
array([[1, 2], [3, 4], [5, 6]])
Let us try to select specific elements like [0,1,2] which is a row index and column index [0,1,0] each element for the corresponding row.
>>> x[[0,1,2],[0,1,0]]
array([1, 4, 5])
Let us select with 0 which gives you the first row.
>>> x[0]
array([1, 2])
Let us select the 0 as row index and 1 as column index which gives as array value of 2
>>> x[[0],[1]]
array([2])
In the same way, if you select for 0,2 will give us an error. As, there is no value for index of 2.
>>> x[[0],[2]]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x[[0],[2]]
IndexError: index 2 is out of bounds for axis 1 with size 2
You can do the add operation which returns the value of particular index after performing the addition.
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[[0],[1]]+1
array([3])
Below operation will change the values in the array and returns the new copy of an array.
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[[0],[1]]+=1
>>> x
array([[1, 3],
[3, 4],
[5, 6]])
 Boolean Indexing:
Boolean Indexing will be used when the result is going to be the outcome of boolean operations.
Example:
>>> x=np.array([[0,1,2],
[3,4,5],
[6,7,8],
[9,10,11]])
>>> x
array([[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8],
[ 9, 10, 11]])
# returns the values which are 0.
>>> x[x ==0]
array([0])
# returns the values which are even numbers.
>>> x[x%2==0]
array([ 0,  2,  4,  6,  8, 10])
>>>