
- 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 Division
NumPy Array Division
NumPy array division refers to the process of dividing two arrays element-wise. In this context, element-wise division means that each element in one array is divided by the corresponding element in another array.
This operation supports broadcasting, allowing for division between arrays of different shapes. Additionally, division can be performed between an array and a scalar, which scales each element of the array accordingly.
Element-wise Division in NumPy
Element-wise division in NumPy refers to dividing each element of one array by the corresponding element in another array. This operation is performed element by element, meaning that the division occurs pairwise between the elements of the two arrays at the same positions.
For element-wise division to work, the two arrays must have the same shape, or they must be broadcastable to a common shape.
In NumPy, the division operator / is used to perform element-wise division. If the arrays have different shapes but are compatible for broadcasting, NumPy will automatically apply broadcasting rules to perform the division.
Example
In the following example, we are dividing each element of array a by the corresponding element of array b −
import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([2, 5, 10]) # Performing element-wise division result = a / b print(result)
Following is the output obtained −
[5. 4. 3.]
Division by a Scalar in NumPy
Division by a scalar in NumPy refers to dividing each element of an array by a single scalar value. This operation applies the division to every element of the array, resulting in a new array where each element has been divided by the scalar.
Example
In this example, we are dividing each element of the array "a" with the scalar "10" −
import numpy as np # Creating an array a = np.array([10, 20, 30]) # Dividing by a scalar result = a / 10 print(result)
This will produce the following result −
[1. 2. 3.]
Broadcasting in Array Division
Broadcasting allows for operations between arrays of different shapes. When performing division between arrays of different shapes, NumPy automatically adjusts the shapes so that the operation can be performed.
When performing array division, broadcasting allows you to divide arrays of different sizes or shapes by automatically expanding the smaller array along the missing dimensions to match the shape of the larger array.
This expansion is done in a way that allows element-wise operations, like division, to be performed without explicitly replicating the data.
Example
In the example below, array "b" is broadcasted to match the shape of array "a", and then element-wise division is performed −
import numpy as np # Creating arrays with different shapes a = np.array([[10, 20, 30], [40, 50, 60]]) b = np.array([10, 5, 2]) # Performing division with broadcasting result = a / b print(result)
Following is the output of the above code −
[[ 1. 4. 15.] [ 4. 10. 30.]]
Handling Division by Zero
When performing division operations in NumPy, one common issue is the possibility of dividing by zero, which can lead to undefined or infinite results. NumPy provides ways to handle such scenarios, either by returning special values (like inf or nan) or by raising warnings or errors depending on the specific use case.
- Positive/Negative Infinity (inf or -inf) − It is returned when a positive or negative number is divided by zero.
- Not a Number (nan) − It is returned when zero is divided by zero.
Example: Basic Division by Zero
Let us see how NumPy handles a simple division by zero −
import numpy as np # Creating an array with a zero element array = np.array([10, 0, -5]) # Dividing a constant by the array result = 100 / array print(result)
NumPy does not raise an error but instead returns "inf" for division by zero −
/home/cg/root/66c57b63ef7f5/main.py:7: RuntimeWarning: divide by zero encountered in divide result = 100 / array [ 10. inf -20.]
Example: Handling Division by Zero Using errstate() Function
You can control how NumPy handles division by zero using np.errstate() function. This function allows you to specify whether to ignore, warn, or raise an error for floating-point errors like division by zero −
import numpy as np # Creating an array with a zero element array = np.array([10, 0, -5]) with np.errstate(divide='ignore', invalid='ignore'): result = 100 / array print(result)
Here, we set the "divide" parameter to "ignore" in the errstate() function to ignore the warning that generally occurs with division by zero. The result still contains "inf", but without any interruption or warning −
/home/cg/root/66c57b63ef7f5/main.py:7: RuntimeWarning: divide by zero encountered in divide result = 100 / array [ 10. inf -20.]
Example: Handling nan Values
When zero is divided by zero, the result is nan (Not a Number). This special value is used to represent undefined or unrepresentable values in floating-point calculations −
import numpy as np # Creating arrays with zero elements numerator = np.array([0, 1, 2]) denominator = np.array([0, 0, 2]) # Performing division result = numerator / denominator print(result)
The result produced is as follows −
[ 10. inf -20.]
Division with Different Data Types
When performing division between arrays of different data types, NumPy automatically promotes the data types to a common type that can safely contain the result.
For example, if you divide an integer array by a float array, the result will be a float array. This type promotion prevents data loss and ensures the precision of the results.
Example
In this example, NumPy promotes the integer array a to a float type to match the data type of array b before performing the division −
import numpy as np # Creating arrays with different data types a = np.array([10, 20, 30], dtype=np.int32) b = np.array([2.5, 5.0, 10.0], dtype=np.float64) # Performing division result = a / b print(result)
We get the output as shown below −
[4. 4. 3.]
Matrix Division in NumPy
Matrix division is not as straightforward as element-wise division or scalar division. However, you can solve for a matrix division-like operation by using matrix multiplication with the inverse of a matrix in NumPy.
Example
In this example, we use the inverse of matrix B to perform a division-like operation in NumPy −
import numpy as np # Creating a matrix A = np.array([[1, 2], [3, 4]]) # Creating another matrix B = np.array([[2, 0], [1, 3]]) # Solving the matrix division A/B # Equivalent to A * B^-1 result = np.dot(A, np.linalg.inv(B)) print(result)
Following is the output obtained −
[[0.16666667 0.66666667] [0.83333333 1.33333333]]
Handling Dimension Mismatch in Division
When performing division operations between arrays in NumPy, dimension mismatch can occur if the arrays do not share compatible shapes. NumPy addresses this issue through broadcasting and raises a ValueError in such case.
Example
In the following example, the shapes of "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([[1, 2], [3, 4]]) # Attempting to divide incompatible arrays result = a / b print(result)
The result produced is as follows −
Traceback (most recent call last): File "/home/cg/root/66c57b63ef7f5/main.py", line 8, in <module> result = a / b ValueError: operands could not be broadcast together with shapes (3,) (2,2)