w3resource

NumPy: Fetch all items from a given array of 4,5 shape which are either greater than 6 and a multiple of 3


Extract items greater than 6 and multiples of 3.

Write a NumPy program to fetch all items from a given array of 4,5 shape which are either greater than 6 and a multiple of 3.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array: array_nums1 from 0 to 19 reshaped into a 4x5 array
array_nums1 = np.arange(20).reshape(4, 5)

# Printing the original array
print("Original arrays:")
print(array_nums1)

# Finding elements greater than 6 and divisible by 3 in the array_nums1
result = array_nums1[(array_nums1 > 6) & (array_nums1 % 3 == 0)]

# Printing elements greater than 6 and divisible by 3 in the array_nums1
print("\nItems greater than 6 and a multiple of 3 of the said array:")
print(result) 

Sample Output:

Original arrays:
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]

Items greater than 6 and a multiple of 3 of the said array:
[ 9 12 15 18]

Explanation:

In the above exercise -

array_nums1 = np.arange(20).reshape(4,5) creates a 1-dimensional NumPy array containing numbers from 0 to 19 and then reshapes it into a 2-dimensional array with 4 rows and 5 columns.

result = array_nums1[(array_nums1>6) & (array_nums1%3==0)]

In the above code -

  • (array_nums1 > 6): This part creates a boolean array with the same shape as array_nums1 where each element is True if the corresponding element in array_nums1 is greater than 6, and False otherwise.
  • (array_nums1 % 3 == 0): This part creates another boolean array with the same shape as array_nums1 where each element is True if the corresponding element in array_nums1 is divisible by 3 (i.e., has a remainder of 0 when divided by 3), and False otherwise.
  • (array_nums1 > 6) & (array_nums1 % 3 == 0): This part combines the two boolean arrays element-wise using the & (and) operator, resulting in a new boolean array with the same shape as array_nums1. An element in the resulting array is True if both corresponding elements in the input boolean arrays are True, and False otherwise.
  • array_nums1[(array_nums1 > 6) & (array_nums1 % 3 == 0)]: This code filters the elements in array_nums1 using the combined boolean array. Only elements corresponding to True values in the boolean array are retained, and the result is a 1-dimensional array containing the filtered elements.
  • 'result' variable stores the 1-dimensional array of filtered elements from array_nums1 that are both greater than 6 and divisible by 3.

Python-Numpy Code Editor: