NumPy: Check whether a Numpy array contains a specified row
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:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to check if a given row exists in a 2D array using np.all and broadcasting.
- Create a function that iterates over rows of a matrix and returns True if an exact match is found.
- Implement a solution that converts both the target row and each row of the array to strings for comparison.
- Test the function on arrays with duplicate rows and near-matches to ensure it only returns exact matches.
Go to:
PREV : Zero out elements below k-th diagonal.
NEXT : Calculate averages without NaN.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.