w3resource

NumPy: Test whether specified values are present in an array

NumPy: Array Object Exercise-65 with Solution

Write a NumPy program to test if specified values are present in an array.

Pictorial Presentation:

Python NumPy: Test whether specified values are present in an array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 2x3 NumPy array 'x' with specific float values
x = np.array([[1.12, 2.0, 3.45], [2.33, 5.12, 6.0]], float)

# Displaying the original array 'x'
print("Original array:")
print(x)

# Checking if 2 is present in the array 'x'
print(2 in x)

# Checking if 0 is present in the array 'x'
print(0 in x)

# Checking if 6 is present in the array 'x'
print(6 in x)

# Checking if 2.3 is present in the array 'x'
print(2.3 in x)

# Checking if 5.12 is present in the array 'x'
print(5.12 in x) 

Sample Output:

Original array:                                                        
[[ 1.12  2.    3.45]                                                   
 [ 2.33  5.12  6.  ]]                                                  
True                                                                   
False                                                                  
True                                                                   
False                                                                  
True    

Explanation:

In the above exercise -

‘x = np.array([[1.12, 2.0, 3.45], [2.33, 5.12, 6.0]], float)’ creates a 2D NumPy array x with the specified floating-point values.

The following statements use the in operator to check if the specified values are present in the array x:

  • print(2 in x): Checks if 2 is present in the array. Prints True because 2.0 is present.
  • print(0 in x): Checks if 0 is present in the array. Prints False because 0 is not present.
  • print(6 in x): Checks if 6 is present in the array. Prints True because 6.0 is present.
  • print(2.3 in x): Checks if 2.3 is present in the array. Prints False because 2.3 is not present.
  • print(5.12 in x): Checks if 5.12 is present in the array. Prints True because 5.12 is present.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 5x5 matrix with row values ranging from 0 to 4.
Next: Write a NumPy program to create a vector of size 10 with values ranging from 0 to 1, both excluded.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.