w3resource

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


Store non-zero unique rows from a matrix.

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:

# Importing NumPy library
import numpy as np

# Creating a NumPy array
arra = np.array([[1, 1, 0],
                 [0, 0, 0],
                 [0, 2, 3],
                 [0, 0, 0],
                 [0, -1, 1],
                 [0, 0, 0]])

# Printing the original array
print("Original array:")
print(arra)

# Creating a set of tuples with all zeros
temp = {(0, 0, 0)}

# Initializing an empty list to store row indices
result = []

# Enumerating through each row as a tuple and its index
for idx, row in enumerate(map(tuple, arra)):
    # Checking if the row is not in the set of all zeros
    if row not in temp:
        # Appending the index to the result list
        result.append(idx)

# Printing non-zero unique rows based on their indices
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]]

Explanation:

In the above exercise -

  • arra = np.array(...): This line creates a 6x3 NumPy array.
  • temp = {(0, 0, 0)}: Creates a set containing the tuple (0, 0, 0) which we want to remove from arra.
  • result = []: This line initializes an empty list that will store the indices of rows in arra that don't match the given tuple.
  • for idx, row in enumerate(map(tuple, arra)): The for loop iterates through the enumerated rows of ‘arra’ after converting each row to a tuple using map(tuple, arra).
  • if row not in temp: checks if the current row (as a tuple) is not in the set temp (i.e., not equal to (0, 0, 0)).
  • If the condition is True, the index (idx) of the current row is appended to the result list.
  • After the loop, arra[result] selects rows of arra using the indices stored in the result list, effectively removing rows that matched the given tuple.
  • Finally print() function prints the modified array ‘arra’, with all rows containing (0, 0, 0) removed.

Pictorial Presentation:

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract rows from a 2D array that are non-zero and unique using np.unique with axis=0.
  • Create a function that filters out rows that contain all zeros before identifying unique rows.
  • Implement a solution that first removes duplicate rows and then excludes any rows containing only zero elements.
  • Test the function on matrices with intermittent zero rows to ensure correct extraction of unique, non-zero rows.

Go to:


PREV : Search for a sub-array in a larger array.
NEXT : Set lower triangles of a 3D array to zero.


Python-Numpy Code Editor:

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

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.