Boolean indexing and fancy indexing are two powerful techniques in NumPy for accessing and manipulating array elements based on specific conditions or using custom index arrays. Let’s explore each of them:
- Boolean Indexing:
Boolean indexing allows you to select elements from an array based on a Boolean condition. The result is a new array containing only the elements that satisfy the condition. Here’s an example:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Boolean indexing to select elements greater than 3 result = arr[arr > 3] print(result)
Output:
[4 5]
In this example, the Boolean condition arr > 3
generates a Boolean mask with True
for elements greater than 3 and False
otherwise. By using this mask as an index for the array arr
, only the elements corresponding to True
values are selected, resulting in a new array [4, 5]
.
Boolean indexing can also be applied to multi-dimensional arrays, allowing you to select specific rows or columns based on conditions.
- Fancy Indexing:
Fancy indexing involves using an array of integers or arrays of indices to access specific elements from an array. This indexing technique provides more flexibility compared to traditional integer indexing. Here’s an example:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Fancy indexing with an array of indices indices = np.array([0, 2, 4]) result = arr[indices] print(result)
Output:
[1 3 5]
In this example, the array indices
contains the indices [0, 2, 4]
. By using this array as an index for arr
, the elements at those indices are selected, resulting in a new array [1, 3, 5]
.
Fancy indexing can be used for both one-dimensional and multi-dimensional arrays, and it allows for more complex indexing patterns by using arrays of indices.
Conclusion:
Both boolean indexing and fancy indexing provide powerful ways to access and manipulate array elements in NumPy, offering flexibility and control in selecting the desired elements based on specific conditions or custom index arrays.