w3resource

NumPy: Get the row numbers in given array where at least one item is larger than a specified value

NumPy: Array Object Exercise-151 with Solution

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:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Generating a NumPy array 'num' containing numbers from 0 to 35 using arange()
num = np.arange(36)

# Reshaping the array 'num' into a 4x9 matrix and assigning it to 'arr1'
arr1 = np.reshape(num, [4, 9])

# Displaying a message indicating the original array will be printed
print("Original array:")

# Printing the original array 'arr1'
print(arr1)

# Using np.where() to find row numbers where at least one element is larger than 10 along axis 1 (rows)
result = np.where(np.any(arr1 > 10, axis=1))

# Displaying a message indicating row numbers where at least one item is larger than 10 will be printed
print("\nRow numbers where at least one item is larger than 10:")

# Printing the row numbers where at least one element is larger than 10
print(result) 

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:

NumPy: Get the row numbers in given array where at least one item is larger than a specified value

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.



Follow us on Facebook and Twitter for latest update.