
- 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 - Element-wise Array Comparisons
Element-wise Comparisons in NumPy
Element-wise comparisons in NumPy allow you to compare each element of one array with the corresponding element of another array or a scalar value.
The comparison is performed across the entire array, and the result is a new array of the same shape where each element is a Boolean (True or False) indicating the outcome of the comparison.
Basic Element-wise Comparison Operations
NumPy supports several basic comparison operations that can be performed element-wise. These include −
- Equality (==): Checks if elements in the two arrays (or an array and a scalar) are equal.
- Inequality (!=): Checks if elements are not equal.
- Greater than (>): Checks if elements in the first array are greater than the corresponding elements in the second array or a scalar.
- Less than (<): Checks if elements in the first array are less than the corresponding elements in the second array or a scalar.
- Greater than or equal to (>=): Checks if elements are greater than or equal to the corresponding elements in the second array or a scalar.
- Less than or equal to (<=): Checks if elements are less than or equal to the corresponding elements in the second array or a scalar.
Example
In the following example, each comparison operation is performed between corresponding elements of "array1" and "array2" −
import numpy as np # Creating two arrays for comparison array1 = np.array([10, 20, 30, 40, 50]) array2 = np.array([15, 20, 25, 40, 55]) # Performing element-wise comparisons equality = array1 == array2 inequality = array1 != array2 greater_than = array1 > array2 less_than = array1 < array2 greater_equal = array1 >= array2 less_equal = array1 <= array2 # Displaying the results print("Equality:", equality) print("Inequality:", inequality) print("Greater than:", greater_than) print("Less than:", less_than) print("Greater than or equal to:", greater_equal) print("Less than or equal to:", less_equal)
The result is a Boolean array indicating the outcome of each comparison as shown below −
Equality: [False True False True False] Inequality: [ True False True False True] Greater than: [False False True False False] Less than: [ True False False False True] Greater than or equal to: [False True True True False] Less than or equal to: [ True True False True True]
Element-wise Comparisons with Scalars
You can also compare an entire array with a single scalar value. The scalar value is compared to each element of the array, and the result is a Boolean array of the same shape.
Example
In this example, each element of "array1" is compared to "30", and the result indicates whether each element is greater than "30" −
import numpy as np # Creating two arrays for comparison array1 = np.array([10, 20, 30, 40, 50]) # Comparing array elements with a scalar value scalar_value = 30 comparison_result = array1 > scalar_value print("Array elements greater than 30:", comparison_result)
This will produce the following result −
Array elements greater than 30: [False False False True True]
Chaining Multiple Comparisons
Chaining multiple comparisons in NumPy involves using logical operators to combine several comparison operations. For instance, you might want to check if the elements of an array fall within a specific range or if they satisfy multiple criteria.
The operations are evaluated in sequence, and the result is a Boolean array where each element indicates whether the combined conditions are met.
In NumPy, you can chain comparisons using logical operators like & (and), | (or), and ~ (not). When chaining comparisons, ensure that each comparison operation is enclosed in parentheses to maintain the correct order of operations. Here is the general syntax for chaining comparisons −
(condition1) & (condition2) & ... & (conditionN)
Example: Chaining Comparisons
In the example below, we are checking if the elements of an array are within a specific range and satisfy additional conditions or not −
import numpy as np # Creating an array array = np.array([5, 10, 15, 20, 25, 30]) # Chaining multiple comparisons result = (array > 10) & (array < 25) & (array % 5 == 0) # Displaying the results print("Array:", array) print("Result of Chained Comparisons:", result)
Following is the output of the above code −
Array: [ 5 10 15 20 25 30] Result of Chained Comparisons: [False False True True False False]
Example: Chaining with Scalar Values
Here, the comparison checks if each element of the array is between "3" and "7", inclusive −
import numpy as np # Creating an array array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Chaining comparisons with scalar values result = (array >= 3) & (array <= 7) # Displaying the results print("Array:", array) print("Result of Chained Comparisons with Scalar:", result)
The output obtained is as shown below −
Array: [1 2 3 4 5 6 7 8 9] Result of Chained Comparisons with Scalar: [False False True True True True True False False]
Using where() Function for Conditional Selection
The np.where() function uses the results of element-wise comparisons to selectively choose elements from one of two arrays (or values). This is particularly useful for filtering or replacing elements based on a condition.
Example
In this example, elements of "array1" greater than "25" are kept, while all others are replaced with "0" −
import numpy as np # Creating an array array1 = np.array([10, 20, 30, 40, 50]) # Using np.where to replace elements based on a condition replaced_array = np.where(array1 > 25, array1, 0) print("Replaced array:", replaced_array)
After executing the above code, we get the following output −
Replaced array: [ 0 0 30 40 50]
Finding Max and Min Elements with Comparisons
Element-wise comparisons can be used in conjunction with functions like np.maximum() and np.minimum() to find the maximum or minimum values between two arrays.
Example
In this example, we use np.maximum() function and np.minimum() function to compare elements of "array1" and "array2", returning arrays of the maximum and minimum values respectively −
import numpy as np # Creating an array array1 = np.array([10, 20, 30, 40, 50]) array2 = np.array([15, 20, 25, 40, 55]) # Finding maximum and minimum values between two arrays max_array = np.maximum(array1, array2) min_array = np.minimum(array1, array2) print("Maximum values:", max_array) print("Minimum values:", min_array)
The result produced is as follows −
Maximum values: [15 20 30 40 55] Minimum values: [10 20 25 40 50]