Fancy Indexing with Arrays of Indices in NumPy

Fancy indexing allows selecting multiple elements of an array using an array of integer indices.

1. Importing NumPy

Before using fancy indexing, import NumPy.

            import numpy as np
        

2. Basic Fancy Indexing

Use an array of indices to access multiple elements at once.

            arr = np.array([10, 20, 30, 40, 50])
            indices = np.array([0, 2, 4])
            selected = arr[indices]
            print(selected)
            # Output: [10 30 50]
        

3. Fancy Indexing on Multi-Dimensional Arrays

Fancy indexing works with 2D arrays to extract specific rows or columns.

            matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
            row_indices = np.array([0, 2])
            selected_rows = matrix[row_indices]
            print(selected_rows)
            # Output:
            # [[10 20 30]
            #  [70 80 90]]
        

4. Selecting Specific Elements

Fancy indexing can be used to select individual elements from a multi-dimensional array.

            row_indices = np.array([0, 1, 2])
            col_indices = np.array([2, 0, 1])
            selected_elements = matrix[row_indices, col_indices]
            print(selected_elements)
            # Output: [30 40 80]
        

5. Modifying Elements Using Fancy Indexing

Fancy indexing allows modification of specific elements.

            arr = np.array([10, 20, 30, 40, 50])
            indices = np.array([1, 3])
            arr[indices] = 99
            print(arr)
            # Output: [10 99 30 99 50]
        

6. Conclusion

Fancy indexing in NumPy provides an efficient way to extract and modify elements using arrays of indices.





Advertisement