
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Array Subtraction
NumPy Array Subtraction
NumPy array subtraction allows you to perform element-wise subtraction between arrays. This operation subtracts corresponding elements of one array from another array of the same shape, producing a new array of the same shape with the subtracted values.
If the arrays have different shapes, NumPy can broadcast the smaller array to match the shape of the larger array under certain conditions.
Element-wise Subtraction in NumPy
Element-wise subtraction is the most basic form of array subtraction in NumPy, where corresponding elements of two arrays are subtracted to produce a new array.
This type of subtraction operates on arrays of the same shape, performing the subtraction operation individually for each pair of elements from the two arrays.
Example
In the following example, we are subtracting each element of array a from the corresponding element of array a −
import numpy as np # Creating two arrays a = np.array([5, 6, 7]) b = np.array([1, 2, 3]) # Performing element-wise subtraction result = a - b print(result)
Following is the output obtained −
[4 4 4]
Subtracting a Scalar to a NumPy Array
When a scalar (a single value) is subtracted from an array, the scalar is broadcasted to match the shape of the array. This means that the scalar is effectively treated as if it were an array of the same shape as the original array, with all elements equal to the scalar value.
Broadcasting explains how NumPy manages arithmetic operations involving arrays of different shapes. When arrays with varying shapes are used in calculations, NumPy automatically adjusts their shapes to be compatible with each other according to the broadcasting rules.
Example
In this example, we are subtracting the scalar "10" from each element of the array "a" −
import numpy as np # Creating an array a = np.array([5, 6, 7]) # Subtracting a scalar result = a - 2 print(result)
This will produce the following result −
[3 4 5]
Subtracting NumPy Arrays of Different Shapes
Broadcasting in NumPy allows for the subtraction of arrays with different shapes by adjusting their dimensions to match each other.
NumPy aligns dimensions for broadcasting by comparing from the rightmost side and moving leftward. Dimensions are compatible if they are equal or if one dimension is 1, which is then expanded to match the other dimension.
When dimensions do not align directly, NumPy extends the smaller array along the mismatched dimensions as needed to fit the shape of the larger array.
Example
In the example below, array "b" is broadcasted to match the shape of array "a", and then element-wise subtraction is performed −
import numpy as np # Creating arrays with different shapes a = np.array([[5, 6, 7], [8, 9, 10]]) b = np.array([1, 2, 3]) # Subtracting arrays with broadcasting result = a - b print(result)
Following is the output of the above code −
[[4 4 4] [7 7 7]]
Subtracting Multi-Dimensional Arrays with Broadcasting
In NumPy, broadcasting allows for arithmetic operations, such as subtraction, between multi-dimensional arrays of different shapes by automatically expanding the dimensions of the smaller array to match the shape of the larger array.
Example
In the example below, we broadcast the one-dimensional array "b" to match the dimensions of the two-dimensional array "a" −
import numpy as np # Creating multi-dimensional arrays a = np.array([[10, 20, 30], [40, 50, 60]]) b = np.array([5, 15, 25]) # Subtracting multi-dimensional arrays with broadcasting result = a - b[np.newaxis, :] print(result)
The output obtained is as shown below −
[[ 5 15 25] [25 35 45]]
Subtracting By Applying Functions with Broadcasting
Broadcasting in NumPy not only allows for direct element-wise arithmetic operations but also facilitates applying functions to arrays with different shapes. With broadcasting, you can use various mathematical functions on arrays of different shapes.
Example
In this example, we are subtracting the scalar "5" from each element of the array "a", and then apply the "sine" function element-wise −
import numpy as np # Creating an array a = np.array([10, 20, 30]) # Applying a function with broadcasting result = np.sin(a - 5) print(result)
After executing the above code, we get the following output −
[-0.95892427 -0.7568025 0.14112001]
Subtracting Incompatible Arrays
If we attempt to subtract incompatible arrays in NumPy, the operation will fail and raise a ValueError. NumPy uses broadcasting for operations between arrays of different shapes, but this is only possible if the shapes are compatible according to specific rules.
Example
In this case, the shapes of arrays "a" and "b" are not compatible for broadcasting, resulting in an error −
import numpy as np # Creating arrays with incompatible shapes a = np.array([10, 20, 30]) b = np.array([[1, 2], [3, 4]]) # Subtracting incompatible arrays result = a - b print(result)
The result produced is as follows −
Traceback (most recent call last):File "/home/cg/root/66a1de2fae52f/main.py", line 8, in <module>result = a - bValueError: operands could not be broadcast together with shapes (3,) (2,2)