NumPy: Check whether a Numpy array contains a specified row
NumPy: Array Object Exercise-155 with Solution
Check if an array contains a specified row.
Write a NumPy program to check whether a Numpy array contains a specified row.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Generating a NumPy array of integers from 0 to 19 (exclusive) and reshaping it to a 4x5 matrix
num = np.arange(20)
arr1 = np.reshape(num, [4, 5])
# Displaying a message indicating the original array
print("Original array:")
print(arr1)
# Checking if [0, 1, 2, 3, 4] is present as a sublist in the array, converting the array to a list using tolist()
print([0, 1, 2, 3, 4] in arr1.tolist())
# Checking if [0, 1, 2, 3, 5] is present as a sublist in the array, converting the array to a list using tolist()
print([0, 1, 2, 3, 5] in arr1.tolist())
# Checking if [15, 16, 17, 18, 19] is present as a sublist in the array, converting the array to a list using tolist()
print([15, 16, 17, 18, 19] in arr1.tolist())
Sample Output:
Original array: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] True False True
Explanation:
In the above code -
num = np.arange(20): This code creates a NumPy array with integers from 0 to 19.
arr1 = np.reshape(num, [4, 5]): This code reshapes the NumPy array 'num' into a 4x5 array (4 rows and 5 columns).
[0, 1, 2, 3, 4] in arr1.tolist(): Convert the NumPy array 'arr1' to a nested list using tolist() and check if the list [0, 1, 2, 3, 4] is present as a row in the list.
[0, 1, 2, 3, 5] in arr1.tolist(): Check if the list [0, 1, 2, 3, 5] is present as a row in the list converted from 'arr1'.
[15, 16, 17, 18, 19] in arr1.tolist(): Check if the list [15, 16, 17, 18, 19] is present as a row in the list converted from 'arr1'.
Note: ndarray.tolist()
Return the array as a (possibly nested) list. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed.
Next: Write a NumPy program to calculate averages without NaNs along a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-155.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics