0
0
NumpyHow-ToBeginner ยท 3 min read

How to Subtract Arrays in NumPy: Simple Guide

To subtract arrays in NumPy, use the - operator or the numpy.subtract() function. Both methods perform element-wise subtraction between arrays of the same shape.
๐Ÿ“

Syntax

You can subtract arrays in two main ways:

  • array1 - array2: Uses the minus operator for element-wise subtraction.
  • numpy.subtract(array1, array2): Uses the NumPy function for subtraction.

Both require arrays to have the same shape or be broadcastable.

python
import numpy as np

result = array1 - array2
# or
result = np.subtract(array1, array2)
๐Ÿ’ป

Example

This example shows how to subtract two arrays element-wise using both the minus operator and numpy.subtract().

python
import numpy as np

array1 = np.array([10, 20, 30])
array2 = np.array([1, 2, 3])

# Using minus operator
result1 = array1 - array2

# Using numpy.subtract function
result2 = np.subtract(array1, array2)

print("Result using - operator:", result1)
print("Result using np.subtract():", result2)
Output
Result using - operator: [ 9 18 27] Result using np.subtract(): [ 9 18 27]
โš ๏ธ

Common Pitfalls

Common mistakes when subtracting arrays include:

  • Trying to subtract arrays of different shapes without broadcasting rules applying, which causes errors.
  • Using Python lists instead of NumPy arrays, which does not support element-wise subtraction directly.

Always ensure arrays are NumPy arrays and compatible in shape.

python
import numpy as np

# Wrong: subtracting lists (raises error)
try:
    result = [1, 2, 3] - [1, 1, 1]
except TypeError as e:
    print("Error:", e)

# Right: convert lists to arrays first
array1 = np.array([1, 2, 3])
array2 = np.array([1, 1, 1])
result = array1 - array2
print("Correct result:", result)
Output
Error: unsupported operand type(s) for -: 'list' and 'list' Correct result: [0 1 2]
๐Ÿ“Š

Quick Reference

OperationSyntaxDescription
Subtract arraysarray1 - array2Element-wise subtraction of two arrays
Subtract arraysnp.subtract(array1, array2)Function form for element-wise subtraction
Broadcastingarray1 - scalarSubtract scalar from each element of array1
โœ…

Key Takeaways

Use the minus operator (-) or np.subtract() for element-wise array subtraction.
Arrays must have the same shape or be broadcastable to subtract.
Convert Python lists to NumPy arrays before subtracting.
Broadcasting allows subtracting a scalar from an array easily.
Errors occur if shapes are incompatible or if using lists directly.