Understanding numpy.subtract() function (5 examples)

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

Overview

Numpy is an essential library for scientific computing in Python, offering a broad array of tools for working with arrays. One of its basic yet powerful tools is the numpy.subtract() function, which performs element-wise subtraction between two arrays. This guide will explore the function in detail through five comprehensive examples, showcasing its capability from simple applications to more advanced use cases.

Basic Usage of numpy.subtract()

At its simplest, numpy.subtract() can be used to subtract two numbers or two arrays of equal size. Here’s how it works:

import numpy as np

# Subtracting two numbers
result = np.subtract(10, 3)
print('Subtracting numbers:', result)

# Subtracting two arrays
array1 = np.array([10, 20, 30])
array2 = np.array([1, 2, 3])
result = np.subtract(array1, array2)
print('Subtracting arrays:', result)

The output will be:

Subtracting numbers: 7 
Subtracting arrays: [9 18 27]

Broadcasting

np.subtract() also supports broadcasting, enabling you to subtract arrays of different shapes. For example, you can subtract a single number from an array or subtract arrays of different dimensions as long as they’re compatible for broadcasting:

import numpy as np

# Subtracting a number from an array
array = np.array([10, 20, 30])
result = np.subtract(array, 2)
print('Number from array:', result)

# Subtracting a 1D array from a 2D array with broadcasting
array1 = np.array([[10, 20, 30], [40, 50, 60]])
array2 = np.array([1, 2, 3])
result = np.subtract(array1, array2)
print('2D from 1D array:', result)

The output clearly demonstrates broadcasting in action:

Number from array: [8 18 28] 
2D from 1D array: [[ 9 18 27] [39 48 57]]

Handling Different Data Types

One of the advantages of using numpy.subtract() is its ability to handle arrays of different data types. When dealing with arrays containing various data types, numpy smartly upcasts to a common type:

import numpy as np

# Creating arrays with different data types
array1 = np.array([1, 2, 3], dtype=np.int32)
array2 = np.array([1.5, 2.5, 3.5], dtype=np.float64)

# Subtracting arrays with different data types
result = np.subtract(array1, array2)
print('Mixed data type subtraction:', result)

This yields a floating-point array, demonstrating numpy’s type promotion: Mixed data type subtraction:

[-0.5 -0.5 -0.5]

Subtracting with Axis Parameter

The numpy.subtract() function can be enhanced with the axis parameter to perform directional subtractions along a specific axis of a multidimensional array. This is particularly useful for operations on matrices or higher-dimensional data structures:

import numpy as np

# Example with axis parameter
matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
matrix2 = np.array([[1, 1, 1], [2, 2, 2]])
result = np.subtract(matrix1, matrix2, axis=0)
print('Subtraction with axis:', result)

The output demonstrates subtraction carried over the specified axis: Subtraction with axis:

[[0 1 2] [2 3 4]]

Practical Application: Image Processing

Moving to a more advanced application, numpy.subtract() can be extensively used in image processing to adjust image brightness, contrast, or for more complex operations like background subtraction in video feeds. Consider an example where we subtract one image from another to highlight differences:

from PIL import Image
import numpy as np

# Loading two images
image1 = Image.open('image1.jpg').convert('L')
image2 = Image.open('image2.jpg').convert('L')

# Converting images to numpy arrays
img_array1 = np.array(image1)
img_array2 = np.array(image2)

# Subtracting images
result_image = np.subtract(img_array1, img_array2)

# Saving the result
Image.fromarray(result_image).save('result.jpg')

While the specific result will depend on the input images, this process is commonly used in various image processing tasks to detect changes or anomalies.

Conclusion

The numpy.subtract() function is a versatile tool that plays a vital role in numerical computing with Python. From basic arithmetic to complex, multidimensional operations, its utility is evident across a wide range of applications. By understanding its behavior and mastering its use, you can enhance your data analysis and scientific computing projects significantly.