Using numpy.add() function (6 examples)

Updated: February 25, 2024 By: Guest Contributor Post a comment

Introduction

The NumPy library in Python offers a vast array of functions for operating on arrays, one of the simplest yet most useful among them is the numpy.add() function. This function performs element-wise addition between two arrays, a core operation in the realm of data science and numerical computing. This tutorial will provide a comprehensive guide on using the numpy.add() function, illustrated with six progressively advanced examples.

Syntax & Parameters of numpy.add()

Before diving into the examples, let’s understand what numpy.add() exactly does. In its essence, numpy.add() takes two input arrays (of compatible shapes) and outputs a new array, where each element is the sum of the elements at the same position in the input arrays. It’s a vectorized way to perform addition, which is more efficient than using a loop in base Python.

Syntax:

numpy.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

The parameters of numpy.add() carry the following significance:

  • x1, x2: Input arrays to be added.
  • out: A location where the result is stored.
  • where: A condition on which the addition is performed. If True (default), the addition is performed on all elements.
  • casting: Controls the casting of types.
  • order: Memory layout of the result.
  • dtype: Specifies the data type of the result.
  • subok: Determines if sub-classes are returned.

Example 1: Basic Addition

Let’s start with the most basic example where we add two arrays containing integers.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.add(a, b)

print(c)

This code will output:

[5 7 9]

Here, numpy.add() performed element-wise addition and returned a new array containing the sums.

Example 2: Adding Arrays of Different Shapes

In this example, we’ll see how numpy.add() handles arrays of different shapes through broadcasting. This feature allows NumPy to perform operations on arrays that do not exactly match in shape but are compatible.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
c = np.add(a, b)

print(c)

The output will be a 2D array:

[[2 3 4]
 [3 4 5]
 [4 5 6]]

This shows how numpy.add() automatically broadcasts the first array across the second one, resulting in a 2D array where each row is the sum of the original array and the corresponding element of the second array.

Example 3: Using the out Parameter

The out parameter of numpy.add() is particularly useful when you want to store the result of the addition in an existing array, thus saving memory.

import numpy as np

result = np.zeros(3)
a = np.array([1, 2, 3])
b = np.array([-1, -2, -3])

np.add(a, b, out=result)

print(result)

Output:

[0 0 0]

This shows that the sum of a and b was stored in the result array, which was initialized with zeros.

Example 4: Addition With Conditions

The where parameter can be used to control where the addition is applied. This allows for conditional operations within the addition process, a powerful feature for selective computations.

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([4, 3, 2, 1])
condition = np.array([True, False, True, False])
c = np.add(a, b, where=condition)

print(c)

Output:

[5 2 5 4]

Here, addition is performed only where condition is True, illustrating how the where parameter enables selective addition.

Example 5: Using dtype to Control Output Type

Specifying the dtype parameter allows you to control the data type of the output array. This is useful when dealing with large numbers or when the precision of the result is important.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.add(a, b, dtype=np.float64)

print(c)

This results in:

[5.0 7.0 9.0]

By specifying dtype=np.float64, we ensure that the output array has the desired data type, providing control over the precision of the computation.

Example 6: Advanced Broadcasting

Our final example delves into more complex broadcasting scenarios, where numpy.add() enables the element-wise addition of arrays that do not initially seem compatible.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([1, 2]).reshape(2,1)
c = np.add(a, b)

print(c)

Output:

[[2 3 4]
 [3 4 5]]

In this advanced example, numpy.add() broadcasts the second array in a way that it becomes compatible with the first, demonstrating the power and flexibility of broadcasting in NumPy operations.

Conclusion

The numpy.add() function is a versatile tool in NumPy’s arsenal, enabling efficient and flexible array operations. Through these examples, ranging from basic to advanced, we’ve explored how numpy.add() can be used to perform element-wise addition across different scenarios, demonstrating its utility in numerical computing and data science work.