w3resource

NumPy: Find and store non-zero unique rows in an array after comparing each row with other row in a given matrix

NumPy: Array Object Exercise-172 with Solution

Write a NumPy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix.

Sample Solution:

Python Code:

import numpy as np
arra = np.array([[ 1,  1,  0],
                 [ 0,  0,  0],
                 [ 0,  2,  3],
                 [ 0,  0,  0],
                 [ 0, -1,  1],
                 [ 0,  0,  0]])

print("Original array:")
print(arra)
temp = {(0, 0, 0)}
result = []
for idx, row in enumerate(map(tuple, arra)):
    if row not in temp:
        result.append(idx)
print("\nNon-zero unique rows:")
print(arra[result])

Sample Output:

Original array:
[[ 1  1  0]
 [ 0  0  0]
 [ 0  2  3]
 [ 0  0  0]
 [ 0 -1  1]
 [ 0  0  0]]

Non-zero unique rows:
[[ 1  1  0]
 [ 0  2  3]
 [ 0 -1  1]]

Pictorial Presentation:

NumPy: Find and store non-zero unique rows in an array after comparing each row with other row in a given matrix.

Python Code Editor:

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

Previous: Write a NumPy program to search the index of a given array in another given array.
Next: Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

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