Arithmetic Operations in NumPy

NumPy provides a wide range of arithmetic operations that can be performed on arrays. These operations include addition, subtraction, multiplication, and division. All these operations are element-wise, meaning they are applied to each element of the arrays individually.

1. Addition

In NumPy, you can add two arrays or a scalar value to an array using the + operator or the np.add() function.

Example of Addition

    import numpy as np
    
    # Create two NumPy arrays
    array1 = np.array([1, 2, 3])
    array2 = np.array([4, 5, 6])
    
    # Perform element-wise addition
    result = array1 + array2
    
    # Display the result
    print("Addition Result:", result)
        

Output:

    Addition Result: [5 7 9]
        

2. Subtraction

You can subtract one array from another or subtract a scalar from an array using the - operator or the np.subtract() function.

Example of Subtraction

    import numpy as np
    
    # Create two NumPy arrays
    array1 = np.array([10, 20, 30])
    array2 = np.array([1, 2, 3])
    
    # Perform element-wise subtraction
    result = array1 - array2
    
    # Display the result
    print("Subtraction Result:", result)
        

Output:

    Subtraction Result: [ 9 18 27]
        

3. Multiplication

NumPy supports element-wise multiplication using the * operator or the np.multiply() function.

Example of Multiplication

    import numpy as np
    
    # Create two NumPy arrays
    array1 = np.array([2, 3, 4])
    array2 = np.array([5, 6, 7])
    
    # Perform element-wise multiplication
    result = array1 * array2
    
    # Display the result
    print("Multiplication Result:", result)
        

Output:

    Multiplication Result: [10 18 28]
        

4. Division

You can divide one array by another or divide an array by a scalar using the / operator or the np.divide() function.

Example of Division

    import numpy as np
    
    # Create two NumPy arrays
    array1 = np.array([10, 20, 30])
    array2 = np.array([2, 4, 6])
    
    # Perform element-wise division
    result = array1 / array2
    
    # Display the result
    print("Division Result:", result)
        

Output:

    Division Result: [5. 5. 5.]
        

Key Notes

  • All arithmetic operations are performed element-wise on the arrays.
  • If you perform operations between arrays of different shapes, NumPy will attempt to broadcast them to compatible shapes.
  • In case of division, dividing by zero will result in inf or NaN, depending on the context.

Conclusion

NumPy simplifies arithmetic operations on arrays. By using operators like +, -, *, and /, you can easily perform element-wise operations on arrays. These operations are crucial when working with large datasets and performing mathematical computations.





Advertisement