w3resource

NumPy: Find rows of a given array of shape that contain elements of each row of another given array of shape

NumPy: Array Object Exercise-189 with Solution

Write a NumPy program to find rows of a given array of shape (8,3) that contain elements of each row of another given array of shape (2,2).

Sample Solution:

Python Code:

import numpy as np
nums1 = np.random.randint(0,6,(6,4))
nums2 = np.random.randint(0,6,(2,3))
print("Original arrays:")
print(nums1)
print("\n",nums2)
temp = (nums1[..., np.newaxis, np.newaxis] == nums2)
rows = (temp.sum(axis=(1,2,3)) >= nums2.shape[1]).nonzero()[0]
print("\nRows of a given array that contain elements of each row of another given array:")
print(rows)

Sample Output:

Original arrays:
[[5 2 5 1]
 [5 4 1 3]
 [0 1 1 1]
 [2 0 4 0]
 [2 5 1 5]
 [4 0 4 0]]

 [[2 3 1]
 [1 1 4]]

Rows of a given array that contain elements of each row of another given array:
[0 1 2 4]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix.
Next: Write a NumPy program to create a record array from a given regular array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]