Easy way to test if each element in a numpy array lies between two values?

Given a NumPy array, we have to check if each element in it lies between two values.
Submitted by Pranit Sharma, on January 19, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a NumPy array that contains some integer values. We need to check that each value of this array lies between two values (say 50 and 100).

Checking whether each element in a numpy array lies between two values

For this purpose, we can simply write our condition on our array and use the logical AND operation between both conditions. It will return True if both the conditions are True and False if any of them is False.

Let us understand with the help of an example,

Python code to check if each element in a numpy array lies between two values

# Import numpy
import numpy as np

# Creating an array
arr = np.arange(10)

# Display original array
print("Original Array:\n",arr,"\n")

# Shuffling array
np.random.shuffle(arr)

# Display result
print("Shuffled array:\n",arr,"\n")

Output

Example: Easy way to test if each element in a numpy array lies between two values?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.