Array Indexing and Slicing in NumPy Framework

NumPy allows powerful indexing and slicing operations to access and modify array elements efficiently. This tutorial covers indexing and slicing techniques with examples.

1. Indexing in NumPy

Indexing is used to access specific elements in an array.

            import numpy as np
            
            arr = np.array([10, 20, 30, 40, 50])
            print("First element:", arr[0])
            print("Last element:", arr[-1])
        

Output:

            First element: 10
            Last element: 50
        

2. Indexing in a 2D Array

For multidimensional arrays, indexing is done using row and column indices.

            arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
            print("Element at row 1, column 2:", arr2d[1, 2])
        

Output:

            Element at row 1, column 2: 6
        

3. Slicing in NumPy

Slicing is used to extract a portion of an array.

            print("Slice from index 1 to 3:", arr[1:4])
        

Output:

            Slice from index 1 to 3: [20 30 40]
        

4. Slicing in a 2D Array

We can slice specific rows and columns in a 2D array.

            print("First two rows and first two columns:\n", arr2d[:2, :2])
        

Output:

            [[1 2]
             [4 5]]
        

Conclusion

NumPy indexing and slicing allow efficient extraction and modification of array elements, making data manipulation easier.





Advertisement