Python – Matrix elements Frequencies Counter

Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using Counter() + sum() + map()
The combination of above methods can be used to perform this task. In this, we perform task of counting elements using Counter() and extending the logic to each row is performed using sum() and map().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Matrix elements Frequencies Counter
# using Counter() + sum() + map()
from collections import Counter
  
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Matrix elements Frequencies Counter
# using Counter() + sum() + map()
res = dict(sum(map(Counter, test_list), Counter()))
  
# printing result 
print ("The frequencies dictionary is : " + str(res))

chevron_right


Output :

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}

 

Method #2 : Using chain() + Counter()
The combination of above functions can be used to perform this task. In this, we flatten the matrix using chain() and compute frequency using Counter().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Matrix elements Frequencies Counter
# using Counter() + chain()
from collections import Counter
import itertools
  
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Matrix elements Frequencies Counter
# using Counter() + chain()
res = dict(Counter(itertools.chain(*test_list)))
  
# printing result 
print ("The frequencies dictionary is : " + str(res))

chevron_right


Output :

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.