The Wayback Machine - https://web.archive.org/web/20240827061924/https://www.geeksforgeeks.org/python-unique-values-in-matrix/
Open In App

Python | Unique values in Matrix

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let’s see certain ways in which this can be achieved. 

Method #1: Using set() + list comprehension The set function can be used to convert the individual list to a non-repeating element list and the list comprehension is used to iterate to each of the lists. 

Python3




# Python3 code to demonstrate
# checking unique values in matrix
# set() + list comprehension
 
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
 
# using set() + list comprehension
# for checking unique values in matrix
res = list(set(i for j in test_matrix for i in j))
 
# printing result
print("Unique values in matrix are : " + str(res))


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time complexity: O(n^2), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of unique elements in the matrix. 

Method #2: Using chain() + set() The chain function performs the similar task that a list comprehension performs but in a faster way as it uses iterators for its internal processing and hence faster. 
 

Python3




# Python3 code to demonstrate
# checking unique values in matrix
# chain() + set()
from itertools import chain
 
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print ("The original matrix is : " + str(test_matrix))
 
# using chain() + set()
# for checking unique values in matrix
res = list(set(chain(*test_matrix)))
 
# printing result
print ("Unique values in matrix are : " + str(res))


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time Complexity: O(n), where n is the total number of elements in the matrix.
Auxiliary Space: O(n), for storing the unique elements in the set.

Method #3 : Using for loop and extend(),sort() methods

Python3




# Python3 code to demonstrate
# checking unique values in matrix
 
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
    x.extend(i)
res = []
for i in x:
    if i not in res:
        res.append(i)
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time complexity: O(n*logn), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of unique elements in the matrix. 

Method #4 : Using Counter() function

Python3




# Python3 code to demonstrate
# checking unique values in matrix
from collections import Counter
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
    x.extend(i)
freq = Counter(x)
res = list(freq.keys())
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time Complexity:O(N*N)
Auxiliary Space: O(N*N)

Method #5: Using operator.countOf() method

Python3




# Python3 code to demonstrate
# checking unique values in matrix
import operator as op
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
    x.extend(i)
res = []
for i in x:
    if op.countOf(res,i)==0:
        res.append(i)
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method #6:Using groupby()

Python3




# Python3 code to demonstrate
# checking unique values in matrix
# using itertools.groupby
import itertools
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
 
# Flatten the matrix
flat_list = [item for sublist in test_matrix for item in sublist]
 
# sorting the list
flat_list.sort()
 
# Grouping the sorted list
grouped_list = [list(group) for key, group in itertools.groupby(flat_list)]
 
# getting unique values in matrix
res = [group[0] for group in grouped_list]
 
# printing result
print("Unique values in matrix are : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method #7: Using numpy.unique() function

Step-by-step approach:

  • Import numpy library.
  • Initialize the matrix using numpy.array() function.
  • Apply numpy.unique() function on the matrix to get the unique values.
  • Convert the returned numpy array to a list using the tolist() method.
  • Print the list of unique values.

Below is the implementation of the above approach:

Python3




import numpy as np
 
# initializing matrix
test_matrix = np.array([[1, 3, 1], [4, 5, 3], [1, 2, 4]])
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
 
# using numpy.unique() for checking unique values in matrix
res = np.unique(test_matrix).tolist()
 
# printing result
print("Unique values in matrix are : " + str(res))


Output: 

The original matrix is : [[1 3 1]
[4 5 3]
[1 2 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time complexity: O(nlogn), where n is the number of elements in the matrix.
Auxiliary space: O(n)

Method #8:Using heapq.merge():

Algorithm
 

  1. Import the heapq module.
  2. Create a NumPy array test_matrix with shape (3, 3) and values [[1, 3, 1], [4, 5, 3], [1, 2, 4]].
  3. Print the original matrix.
  4. Use heapq.merge() to merge the rows of test_matrix into a single iterator of sorted elements.
  5. Convert the iterator to a set to eliminate duplicates.
  6. Print the unique elements of the matrix.

Python3




import heapq
import numpy as np
 
# initializing matrix
 
test_matrix = np.array([[1, 3, 1], [4, 5, 3], [1, 2, 4]])
 
 
# printing the original matrix
 
print("The original matrix is : " + str(test_matrix))
 
 
# using heapq.merge() and set() for checking unique values in matrix
 
res = set(heapq.merge(*test_matrix))
 
 
# printing result
 
print("Unique values in matrix are : " + str(list(res)))
#This code is contributed by Rayudu


Output:
The original matrix is : [[1 3 1]
[4 5 3]
[1 2 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Time Complexity

The time complexity of the code is determined by the most time-consuming operation, which is heapq.merge(). The time complexity of heapq.merge() is O(k * log(n)), where k is the total number of elements in the matrix and n is the number of rows in the matrix. Therefore, the overall time complexity of the code is O(k * log(n)).

Auxiliary Space

The space complexity of the code is determined by the memory used by the data structures created during the execution of the code. The code creates a NumPy array to store the matrix, which requires O(n^2) space, where n is the number of rows or columns in the array. The heapq.merge() function also creates a heap to store the merged elements, which requires O(k) space, where k is the total number of elements in the matrix. Finally, the code creates a set to store the unique elements, which requires O(k) space. Therefore, the overall space complexity of the code is O(n^2 + k).

 Method #9:Using reduce():

Algorithm:

  1. Initialize the test_matrix variable with a 2D list.
  2. Print the original matrix using the print() function.
  3. Import the chain and set functions from the itertools module.
  4. Use chain() to flatten the 2D matrix into a single list.
  5. Use set() to get the unique elements from the flattened list.
  6. Convert the resulting setback to a list using the list() function.
  7. Print the list of unique values using the print() function.

Below is the implementation of the above approach:

Python3




from functools import reduce
from itertools import chain
 
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
 
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
 
# Using reduce() and set() to get
# unique values in matrix
res = list(reduce(lambda a, b: set(a) | set(b), test_matrix))
 
# printing result
print("Unique values in matrix are:", res)
 
# This  code is contributed by Jyothi pinjala.


Output

The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are: [1, 2, 3, 4, 5]

Time Complexity:

  • The chain() function is used to flatten the 2D matrix, which takes O(N) time, where N is the total number of elements in the matrix.
  • The set() function takes O(N) time to create a set of unique elements.
  • Converting the set back to a list using the list() function takes O(N) time.

Therefore, the overall time complexity of the code is O(N).

Space Complexity:

  • The test_matrix variable takes O(N) space to store the 2D matrix.
  • The res variable takes O(M) space to store the unique elements, where M is the number of unique elements in the matrix.
  • The chain() function and the set() function also take O(N) space.

Therefore, the overall space complexity of the code is O(N).



Similar Reads

Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python | Get Unique values from list of dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let's discuss certain ways in which this task can be performed. Method #1 : Using set(
4 min read
Python - Unique values Multiplication
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its product. This operations has large no. of applications and hence it’s knowledge is good to have. Method 1 : Naive method + loop In naive method, we simply traverse the list and append the first occurrence of the
5 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Python - Unique Values of Key in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the unique values of a particular key in Dictionary List. This kind of problem in very common in day-day programming and web development domain. Let us discuss certain ways in which this task can be performed. Input : test_list = [{'geeks': 10, 'for
7 min read
Python - Key with maximum unique values
Given a dictionary with a values list, extract the key whose value has the most unique values. Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]} Output : "Gfg" Explanation : "Gfg" having max unique elements i.e 5. Input : test_dict = {"Gfg" : [5, 7, 7, 7, 7], "is" : [6, 7, 7, 7], "Best" : [9, 9, 6, 5, 5
8 min read
Counting number of unique values in a Python list
Let us see how to count the number of unique values in a Python list. Examples : Input : 10 20 10 30 40 40Output : 2Explanation : Only 2 elements, 20 and 30 are unique in the list. Input : 'geeks' 'for' 'geeks'Output : 1 Approach 1: Traversing the list and counting the frequency of each element using a dictionary, finally counting the elements for
6 min read
Python - Unique values count of each Key
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key. Example: Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6}, {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg has 1 and 7 as unique elements, hence 2.Input : test
7 min read
Python | Get unique values from a list
In this article, we will explore various techniques and strategies for efficiently extracting distinct elements from a given list. By delving into methods ranging from traditional loops to modern Pythonic approaches with Python. Input : [1,2, 1, 1, 3, 4, 3, 3, 5 ]Output : [1, 2, 3, 4, 5] Explaination: The output only contains the unique element fro
9 min read
Splitting Cells and Counting Unique Values in Python List
In data processing, especially when dealing with tabular data, it's common to encounter cells containing multiple values separated by delimiters like commas or semicolons. Splitting these cells and counting the unique values can provide valuable insights and is a frequent task in data analysis. In this article, we will explore three different metho
2 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python - Test if all elements are unique in columns in a Matrix
Given a Matrix, test if all columns contain unique elements. Input : test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]] Output : True Explanation : 3, 1, 4; 4, 2, 1; 5, 4, 10; All elements are unique in columns. Input : test_list = [[3, 4, 5], [3, 2, 4], [4, 1, 10]] Output : False Explanation : 3, 3, 4; 3 repeated twice. Method #1 : Using loop + set()
5 min read
How to count unique values inside a list
There are several methods for finding or counting unique items inside a list in Python. Here we'll discuss 3 methods. Method 1: The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start
3 min read
Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
Count unique values with Pandas per groups
Prerequisites: Pandas In this article, we are finding and counting the unique values present in the group/column with Pandas. Unique values are the distinct values that occur only once in the dataset or the first occurrences of duplicate values counted as unique values. Approach:Import the pandas library.Import or create dataframe using DataFrame()
7 min read
Pandas - Find unique values from multiple columns
Prerequisite: Pandas In this article, we will discuss various methods to obtain unique values from multiple columns of Pandas DataFrame. Method 1: Using pandas Unique() and Concat() methods Pandas series aka columns has a unique() method that filters out only unique values from a column. The first output shows only unique FirstNames. We can extend
3 min read
How to count unique values in a Pandas Groupby object?
Here, we can count the unique values in Pandas groupby object using different methods. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using Pandas. Method 1: Count unique values using nunique() The Pandas dataframe.nunique() function returns a series with the specified axis's total number of u
3 min read
How to count the frequency of unique values in NumPy array?
Let's see How to count the frequency of unique values in the NumPy array. Python’s Numpy library provides a numpy.unique() function to find the unique elements and their corresponding frequency in a NumPy array. numpy.unique() Syntax Syntax: numpy.unique(arr, return_counts=False) Return: Sorted unique elements of an array with their corresponding f
4 min read
Get unique values from a column in Pandas DataFrame
The unique() function removes all duplicate values on a column and returns a single value for multiple same values. In this article, we will discuss how we can get unique values from a column in Pandas DataFrame. # Get the unique values of any columndf.ColumnName.unique()Pandas Unique Values in ColumnCreating a Pandas Dataframe with Duplicate Eleme
5 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Extract ith column values from jth column values
Sometimes, while working with Python Matrix, we can have a problem in which we need to extract ith column values from comparing values from jth column. This kind of problem can occur in domains such as school programming or web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [[4, 5, 6], [2, 5, 7], [9
8 min read
Python - Extract values of Particular Key in Nested Values
Given a dictionary with nested dictionaries as values, extract all the values with of particular key. Input : test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}}, temp = "b" Output : [9, 10, 19] Explanation : All values of "b" key are extracted. Input : test_dict = {'Gfg' :
4 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Python - Remove keys with Values Greater than K ( Including mixed values )
Given a dictionary with key-value pairs, remove all the keys with values greater than K, including mixed values. Input : test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}, K = 7 Output : {'Gfg' : 3, 'for' : 6, 'geeks' : 'CS'} Explanation : All values greater than K are removed. Mixed value is retained. Input : test_dict = {'
4 min read
Python - Assign values to Values List
Given 2 dictionaries, assign values to value list elements mapping from dictionary 2. Input : test_dict = {'Gfg' : [3, 6], 'best' :[9]}, look_dict = {3 : [1, 5], 6 : "Best", 9 : 12} Output : {'Gfg': {3: [1, 5], 6: 'Best'}, 'best': {9: 12}} Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Input : test_dict = {'Gfg' : [3, 6]}, look_di
6 min read
Mapping external values to dataframe values in Pandas
Mapping external values to a dataframe means using different sets of values to add to that dataframe by keeping the keys of the external dictionary as same as the one column of that dataframe. To add external values to dataframe, we use a dictionary that has keys and values which we want to add to the dataframe. By adding external values in the dat
3 min read
Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 min read
Sort a String in decreasing order of values associated after removal of values smaller than X
Given an integer X and a string str consisting of space-separated texts and numbers placed alternately, the task is to sort the string such that texts and numbers appear in decreasing order of numbers associated after removal of all numbers less than X. If two strings have the same values then sort them in the lexicographic order of the string. Exa
8 min read