w3resource

NumPy: Test whether each element of a 1-D array

NumPy: Array Object Exercise-17 with Solution

Write a NumPy program to test whether each element of a 1-D array is also present in a second array.

Pictorial Presentation:

Python NumPy: Test whether each element of a 1-D array

Sample Solution:

Python Code:

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

# Creating an array 'array1' using NumPy
array1 = np.array([0, 10, 20, 40, 60])

# Printing the contents of 'array1'
print("Array1: ", array1)

# Creating a Python list 'array2'
array2 = [0, 40]

# Printing the contents of 'array2'
print("Array2: ", array2)

# Comparing each element of 'array1' with 'array2'
print("Compare each element of array1 and array2")
print(np.in1d(array1, array2))

Sample Output:

Array1:  [ 0 10 20 40 60]                                              
Array2:  [0, 40]                                                       
Compare each element of array1 and array2                              
[ True False False  True False]

Explanation:

In the above code –

array1 = np.array([0, 10, 20, 40, 60]): Creates a NumPy array with elements 0, 10, 20, 40, and 60.

array2 = [0, 40]: Creates a Python list with elements 0 and 40.

print(np.in1d(array1, array2)): The np.in1d function checks if each element of ‘array1’ is present in ‘array2’. It returns a boolean array of the same shape as ‘array1’, with True at positions where the element is present in ‘array2’ and False otherwise. The output will be [ True False False True False]

Python-Numpy Code Editor:

Previous: Write a NumPy program to find the number of elements of an array, length of one array element in bytes and total bytes consumed by the elements
Next: Write a NumPy program to find common values between two arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-17.php