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
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:
Python-Numpy Code Editor:
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 Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-172.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics