w3resource

NumPy: Extract rows with unequal values from 10x3 matrix

NumPy: Array Object Exercise-188 with Solution

Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix.

Sample Solution:

Example-1:

Python Code:

import numpy as np
nums = np.random.randint(0,4,(6,3))
print("Original vector:")
print(nums)
new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1)
result = nums[~new_nums]
print("\nRows with unequal values:")
print(result)

Sample Output:

Original vector:
[[3 2 0]
 [2 3 1]
 [2 0 3]
 [3 3 1]
 [2 1 1]
 [3 0 2]]

Rows with unequal values:
[[3 2 0]
 [2 3 1]
 [2 0 3]
 [3 3 1]
 [2 1 1]
 [3 0 2]]

Example-2:

Python Code:

import numpy as np
nums = np.array([(1,1,1),
              (1,1,1),
              (1,2,3)])
print("Original vector:")
print(nums)
new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1)
result = nums[~new_nums]
print("\nRows with unequal values:")
print(result)

Sample Output:

Original vector:
[[1 1 1]
 [1 1 1]
 [1 2 3]]

Rows with unequal values:
[[1 2 3]]

Python Code Editor:

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

Previous:Write a NumPy program to convert a given vector of integers to a matrix of binary representation.
Next: 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).

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]