How to Use Fancy Indexing in NumPy for Easy Data Selection
In NumPy,
fancy indexing lets you select multiple elements from an array using lists or arrays of indices inside square brackets. It is useful for picking specific rows, columns, or elements in any order or with repetition.Syntax
Fancy indexing uses arrays or lists of integers or booleans inside square brackets to select elements from a NumPy array.
array[indices]: Select elements at the given positions.indicescan be a list or NumPy array of integers.- Multiple index arrays can select elements in multiple dimensions.
python
import numpy as np arr = np.array([10, 20, 30, 40, 50]) indices = [1, 3, 4] selected = arr[indices] print(selected)
Output
[20 40 50]
Example
This example shows how to use fancy indexing to select specific rows and columns from a 2D array.
python
import numpy as np matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) row_indices = [0, 2] col_indices = [1, 2] # Select rows 0 and 2, columns 1 and 2 result = matrix[np.ix_(row_indices, col_indices)] print(result)
Output
[[2 3]
[8 9]]
Common Pitfalls
One common mistake is mixing fancy indexing with slicing incorrectly, which can lead to unexpected shapes or results.
Also, using multiple index arrays inside a single bracket selects elements element-wise, not as a grid.
For example, arr[[0,1], [1,2]] selects elements at (0,1) and (1,2), not a 2x2 block.
python
import numpy as np arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # Wrong: tries to select a block but selects diagonal elements instead wrong = arr[[0,1], [1,2]] print('Wrong selection:', wrong) # Right: use np.ix_ to select a block right = arr[np.ix_([0,1], [1,2])] print('Right selection:\n', right)
Output
Wrong selection: [20 60]
Right selection:
[[20 30]
[50 60]]
Quick Reference
- Single dimension:
arr[[1,3,4]]selects elements at positions 1, 3, and 4. - Multiple dimensions:
arr[[0,2], [1,2]]selects elements at (0,1) and (2,2). - Block selection: use
np.ix_to select a grid of rows and columns. - Boolean indexing: use boolean arrays to select elements where condition is True.
Key Takeaways
Fancy indexing uses arrays or lists of indices to select multiple elements from NumPy arrays.
Multiple index arrays inside one bracket select elements element-wise, not as a block.
Use np.ix_ to select a rectangular block of rows and columns in 2D arrays.
Mixing slicing and fancy indexing requires care to get expected shapes.
Boolean arrays can also be used for fancy indexing to filter elements.