Python

NumPy Difference Between Two Arrays

This article will discuss the NumPy subtract() function that allows us to return the difference between two arrays.

In simple terms, the function performs an element-wise subtraction between two input arrays.

Let us explore.

Function Syntax

The function syntax is as shown in the code snippet below:

numpy.subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'subtract'>

Essential Function Parameter

The function accepts various parameters, as shown in the above syntax. However, the following are the essential ones:

  1. x1 and x2 – refer to the arrays or array_like objects whose difference needs to be calculated.
  2. out – the output arrays to store the resulting value.
  3. where – specifies the condition that is broadcasted over the input.
  4. kwargs – other keyword-only arguments. Check the docs.

Function Return Value

The function will then return the element-wise difference of the input arrays. If both input values are scalars, the function will also return a scalar value.

Example #1

The code below shows how to use the NumPy subtract() function with two scalar values.

# import numpy
import numpy as np
print(f"difference: {np.subtract(10,4)}")

The code above should return the scalar difference as shown in the output below:

difference: 6

Example #2

In the example below, we use the subtract() function with 2d arrays as shown:

x1 = np.array([[10,20,30], [40,50,60]])
x2 = np.array([[1,2,3], [4,5,6]])
print(f"difference:\n {np.subtract(x1, x2)}")

The code above returns the element-wise difference between the two arrays as shown:

difference:
 [[ 9 18 27]
 [36 45 54]]

Example #3

You can also replace the subtract function with the – operator. An example is as demonstrated below:

x1 = np.array([[10,20,30], [40,50,60]])
x2 = np.array([[1,2,3], [4,5,6]])
print(f"difference:\n {x1 - x2}")

The resulting output is similar to using the subtract function as:

difference:
 [[ 9 18 27]
 [36 45 54]]

Conclusion

This article explored how to determine the element-wise difference between two arrays using the NumPy subtract() function.

Thanks for reading & Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list