How to Perform Basic Arithmetic Operations with NumPy

Updated: January 23, 2024 By: Guest Contributor Post a comment

Overview

NumPy is an essential Python library for performing scientific computing. It offers a powerful N-dimensional array object and a variety of tools for working with these arrays. If you’re doing any sort of data analysis or work with numerical data in Python, learning how to use NumPy effectively is vital.

In this tutorial, you will learn the basics of performing arithmetic operations on NumPy arrays. These operations are element-wise, which means the operation is performed between each element pair from two arrays. We’ll cover addition, subtraction, multiplication, division, and more complex operations.

Setting Up NumPy

To get started, you’ll need to have NumPy installed. If you haven’t done so, you can install it using pip:

pip install numpy

Once installed, you can import NumPy into your Python script like this:

import numpy as np

Creating Arrays

Before we dive into arithmetic operations, it’s important to understand how to create a NumPy array:

import numpy as np

# Create a one-dimensional array
a = np.array([1, 2, 3, 4])

# Create a two-dimensional array
b = np.array([[1, 2, 3], [4, 5, 6]])

Array Addition

Adding two NumPy arrays is as simple as using the + operator:

import numpy as np

# Initialize arrays
a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

# Element-wise addition
result = a + b
print(result)  # Output: [5 7 9]

This operation adds the corresponding elements of both arrays. It requires arrays of the same shape or arrays that can be broadcasted to a common shape.

Array Subtraction

Subtraction is performed using the - operator:

# Subtracting arrays
result = b - a
print(result)  # Output: [3 3 3]

Similar to addition, subtraction is element-wise and both arrays must have the same shape or be broadcastable.

Array Multiplication

The element-wise multiplication of two arrays uses the * operator:

# Multiplying arrays
c = a * b
print(c)  # Output: [ 4 10 18]

This multiplies each element of one array by the corresponding element of another array. The asterisk * is used for this operation, not to be confused with matrix multiplication which uses the @ operator or the np.dot() function.

Array Division

Array division is performed with the / operator:

# Dividing arrays
d = b / a
print(d)  # Output: [4. 2.5 2.]

Just as with multiplication, this is an element-wise operation that divides each element of one array by the corresponding element of another array.

More Complex Operations

NumPy also supports other more complex arithmetic operations. For example, we can perform exponentiation and modulo operations:

# Exponentiation
exp = a**2
print(exp)  # Output: [1 4 9 16]

# Modulo operation
mod = b % a
print(mod)  # Output: [0 1 0]

NumPy also includes a comprehensive set of mathematical functions that can perform operations on arrays, such as np.sqrt() for square roots, np.log() for natural logarithms, and many more.

Broadcasting

Broadcasting describes how arrays of different shapes can be treated during arithmetic operations. The smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting rules apply to all element-wise operations, not just arithmetic ones.

An example of broadcasting:

# Broadcasting an array with a scalar
e = np.array([1, 2, 3])
f = e * 2
print(f)  # Output: [2 4 6]

Here, the scalar value 2 is broadcast across the array e.

Handling Different Shapes

When the shapes of the arrays don’t align for broadcasting, NumPy will raise a ValueError. Here’s an example where shapes do not match:

# This will result in a ValueError
try:
    a = np.array([1,2,3])
    b = np.array([1,2])
    a + b
except ValueError as e:
    print(e)  # Dimensions must be equal

Conclusion

This tutorial covered the basics of performing arithmetic operations with NumPy. By now, you should have a good understanding of how these operations can be used with arrays. NumPy’s array processing capabilities are much faster and more efficient than native Python lists or loops, making it an invaluable tool in your data science arsenal. As you become more familiar with NumPy, you will discover many more sophisticated operations and techniques that can be applied to your data.