NumPy: Get the row numbers in given array where at least one item is larger than a specified value
Get rows where elements are larger than a specified value.
Write a NumPy program to get the row numbers in a given array where at least one item is larger than a specified value.
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 20 21 22 23 24 25 26] [27 28 29 30 31 32 33 34 35]] Row numbers where at least one item is larger than 10: (array([1, 2, 3]),)
Explanation:
In the above code -
num = np.arange(36): This line creates a 1D NumPy array called ‘num’ with elements from 0 to 35.
arr1 = np.reshape(num, [4, 9]): This line reshapes the num array into a 2D array arr1 with 4 rows and 9 columns.
result = np.where(np.any(arr1>10, axis=1)): This line finds the indices of the rows in arr1 where at least one element is greater than 10.
- arr1 > 10 creates a boolean array with the same shape as ‘arr1’, with True values where the corresponding element in ‘arr1’ is greater than 10 and False otherwise.
- np.any(arr1>10, axis=1) reduces the boolean array along the columns (axis=1), returning a 1D boolean array of length 4 (the number of rows in arr1). Each element in this 1D array is True if there's at least one True value in the corresponding row of the boolean array, and False otherwise.
- np.where(np.any(arr1>10, axis=1)) returns the indices of the True values in the 1D boolean array.
Pictorial Presentation:
For more Practice: Solve these Related Problems:
- Write a NumPy program to return the indices of rows in a 2D array where all elements exceed a given threshold.
- Create a function that identifies rows containing at least two elements above a specified value.
- Implement a solution using boolean masking to extract row indices where the maximum element is greater than a given number.
- Use np.any along axis 1 to filter rows with any element surpassing a dynamic threshold, then return the row indices.
Python-Numpy Code Editor:
Previous: Write a NumPy program to swap columns in a given array.Next: Write a NumPy program to calculate the sum of all columns of a 2D numpy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics