Introduction to NumPy Framework

NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.

Installing NumPy

To use NumPy, you need to install it first. You can install it using pip:

            pip install numpy
        

Creating NumPy Arrays

NumPy provides the array function to create arrays. Below is an example:

            import numpy as np
            
            # Creating a 1D array
            arr = np.array([1, 2, 3, 4, 5])
            print(arr)
        

Output:

            [1 2 3 4 5]
        

Basic Operations on Arrays

NumPy allows element-wise arithmetic operations:

            a = np.array([1, 2, 3])
            b = np.array([4, 5, 6])
            
            print(a + b)  # Addition
            print(a - b)  # Subtraction
            print(a * b)  # Multiplication
            print(a / b)  # Division
        

Output:

            [5 7 9]
            [-3 -3 -3]
            [ 4 10 18]
            [0.25 0.4  0.5 ]
        

Array Shape and Reshaping

You can check the shape of an array and reshape it as needed:

            c = np.array([[1, 2, 3], [4, 5, 6]])
            print(c.shape)  # Output: (2, 3)
            
            d = c.reshape(3, 2)
            print(d)
        

Output:

            (2, 3)
            [[1 2]
             [3 4]
             [5 6]]
        

Generating Special Arrays

NumPy provides functions to generate arrays:

            print(np.zeros((2, 2)))  # 2x2 array of zeros
            print(np.ones((3, 3)))   # 3x3 array of ones
            print(np.eye(3))         # 3x3 identity matrix
            print(np.arange(0, 10, 2))  # Array with step size 2
        

Output:

            [[0. 0.]
             [0. 0.]]
            
            [[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]
            
            [[1. 0. 0.]
             [0. 1. 0.]
             [0. 0. 1.]]
            
            [0 2 4 6 8]
        

Conclusion

NumPy is an essential library for numerical computing, providing powerful array manipulation capabilities. Learning NumPy will greatly enhance your ability to work with data in Python.





Advertisement