Numpy Advanced Indexing
# NumPy Advanced Indexing
NumPy provides more indexing methods than standard Python sequences.
In addition to the integer and slice indexing seen previously, arrays can be indexed using integer arrays, boolean indexing, and fancy indexing.
Advanced indexing in NumPy refers to using integer arrays, boolean arrays, or other sequences to access array elements. Compared to basic indexing, advanced indexing can access any element in an array and can be used for complex operations and modifications on the array.
### Integer Array Indexing
Integer array indexing refers to using an array to access elements of another array. Each element in this array is an index value for a certain dimension in the target array.
The following example retrieves the elements at positions **(0,0), (1,1), and (2,0)** in the array.
## Example
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]])y = x[[0,1,2], [0,1,0]]print(y)
The output is:
The following example retrieves the four corner elements of a 4X3 array. The row indices are [0,0] and [3,3], while the column indices are [0,2] and [0,2].
## Example
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 four corner elements of this array are:')print(y)
The output is:
Our array is:[ ]The four corner elements of this array are:[ ]
The returned result is an ndarray object containing each corner element.
Slicing with `:` or `...` can be combined with index arrays. For example:
## Example
import numpy as np a = np.array([[1,2,3], [4,5,6],[7,8,9]])b = a[1:3, 1:3]c = a[1:3,[1,2]]d = a[...,1:]print(b)print(c)print(d)
The output is:
[ ][ ][ ]
### Boolean Indexing
We can index the target array using a boolean array.
Boolean indexing uses boolean operations (e.g., comparison operators) to obtain an array of elements that meet specified conditions.
The following example retrieves elements greater than 5:
## Example
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')# Now we will print elements greater than 5 print('Elements greater than 5 are:')print(x[x>5])
The output is:
Our array is:[ ]Elements greater than 5 are:
The following example uses the `~` (complement operator) to filter out NaN.
## Example
import numpy as np a = np.array([np.nan, 1,2,np.nan,3,4,5])print(a[~np.isnan(a)])
The output is:
[ 1. 2. 3. 4. 5.]
The following example demonstrates how to filter out non-complex numbers from an array.
## Example
import numpy as np a = np.array([1, 2+6j, 5, 3.5+5j])print(a[np.iscomplex(a)])
The output is:
[2.0+6.j 3.5+5.j]
### Fancy Indexing
Fancy indexing refers to using integer arrays for indexing.
**Fancy indexing uses the values of the index array as subscripts for a certain axis of the target array to retrieve values.**
When using a one-dimensional integer array as an index, if the target is a one-dimensional array, the result of the indexing is the elements at the corresponding positions. If the target is a two-dimensional array, it corresponds to the rows at the given subscripts.
Fancy indexing is different from slicing; it always copies the data into a new array.
### One-Dimensional Array
A one-dimensional array has only one axis, **axis = 0**, so values are taken along the **axis = 0** axis:
## Example
import numpy as np
x = np.arange(9)
print(x)
# Read elements at specified indices in a one-dimensional array
print("-------Read elements at specified indices-------")
x2 = x[[0,6]]# Using fancy indexing
print(x2)
print(x2)
print(x2)
The output is:
-------Read elements at specified indices-------06
### Two-Dimensional Array
1. Passing an ordered index array
## Example
import numpy as np x=np.arange(32).reshape((8,4))print(x)# Read specified rows in a two-dimensional array print("-------Read specified rows-------")print(x[[4,2,1,7]])
print (x[[4,2,1,7]]) outputs the rows corresponding to indices **4, 2, 1, 7**, and the output is:
[ ]-------Read specified rows-------[ ]
2. Passing a reversed index array
## Example
import numpy as np x=np.arange(32).reshape((8,4))print(x[[-4,-2,-1,-7]])
The output is:
[ ]
3. Passing multiple index arrays (using `np.ix_`)
The `np.ix_` function takes two arrays and produces a mapping of their Cartesian product.
The Cartesian product in mathematics refers to the Cartesian product of two sets X and Y, also known as the direct product, denoted as **XΓY**, where the first object is a member of X and the second object is one of all possible ordered pairs of members of Y.
For example, **A={a,b}, B={0,1,2}**, then:
AΓB={(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)} BΓA={(0, a), (0, b), (1, a), (1, b), (2, a), (2, b)}
## Example
import numpy as np x=np.arange(32).reshape((8,4))print(x[np.ix_([1,5,7,2],[0,3,1,2])])
The output is:
[ ]
YouTip