
- 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 Addition
NumPy Array Addition
NumPy array addition allows you to perform element-wise addition between arrays. This operation adds corresponding elements from two arrays of the same shape, producing a new array of the same shape with the summed 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 Addition in NumPy
Element-wise addition is the most basic form of array addition in NumPy, where corresponding elements of two arrays are added together to produce a new array.
This type of addition operates on arrays of the same shape, performing the addition operation individually for each pair of elements from the two arrays.
Example
In the following example, we are adding each element of array a is to the corresponding element of array b −
import numpy as np # Creating two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Performing element-wise addition result = a + b print(result)
Following is the output obtained −
[5 7 9]
Adding a Scalar to a NumPy Array
When a scalar (a single value) is added to 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 describes how NumPy handles arrays with different shapes during arithmetic operations. When arrays of different shapes are involved in operations, NumPy automatically adjusts their shapes to match each other, following specific broadcasting rules.
Example
In this example, we are adding the scalar "10" to each element of the array "a" −
import numpy as np # Creating an array a = np.array([1, 2, 3]) # Adding a scalar result = a + 10 print(result)
This will produce the following result −
[11 12 13]
Adding NumPy Arrays of Different Shapes
Broadcasting in NumPy allows for the addition of arrays with different shapes by adjusting their dimensions to match each other.
NumPy aligns the dimensions of arrays for broadcasting by comparing dimensions from the rightmost side and working backward. Two dimensions are considered compatible if they are equal or if one of them is 1, in which case it is broadcasted to match the other dimension.
When dimensions do not directly match, NumPy stretches the smaller array along the mismatched dimensions as necessary to match 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 addition is performed −
import numpy as np # Creating arrays with different shapes a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) # Adding arrays with broadcasting result = a + b print(result)
Following is the output of the above code −
[[11 22 33] [14 25 36]]
Adding Multi-Dimensional Arrays with Broadcasting
In NumPy, broadcasting allows for arithmetic operations, such as addition, between multi-dimensional arrays of different shapes by automatically expanding the dimensions of the smaller array to match the larger array's shape.
This process involves aligning dimensions from the rightmost side and stretching the smaller array's dimensions as needed.
Example
In the example below, we broadcast the one-dimensional array "a" to match the dimensions of the two-dimensional array "b" −
import numpy as np # Creating multi-dimensional arrays a = np.array([1, 2, 3]) b = np.array([[10], [20], [30]]) # Adding multi-dimensional arrays with broadcasting result = a + b print(result)
The output obtained is as shown below −
[[11 12 13] [21 22 23] [31 32 33]]
Adding By Applying Functions with Broadcasting
Broadcasting in NumPy not only simplifies direct element-wise arithmetic operations but also allows for applying functions to arrays of different shapes. Using broadcasting, you can apply various mathematical functions across arrays with differing shapes.
Example
In this example, we are adding the scalar "10" to each element of the array "a", and then apply the "sine" function element-wise −
import numpy as np # Creating an array a = np.array([1, 2, 3]) # Applying a function with broadcasting result = np.sin(a + 10) print(result)
After executing the above code, we get the following output −
[-0.99999021 -0.53657292 0.42016704]
Adding Incompatible Arrays
If we attempt to add 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.
Broadcasting works by aligning the dimensions of the arrays starting from the rightmost dimension and working backward. For two dimensions to be compatible, they must either be equal or one of them must be 1 (in which case it is broadcasted to match the other dimension).
If the shapes of the arrays do not meet these criteria, broadcasting cannot occur, and the operation results in an error.
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([1, 2, 3]) b = np.array([[10, 20], [30, 40]]) # Attempting to add 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)