Find Most Common Element in Each Column in a 2D List - Python
Last Updated :
18 Jan, 2025
We are given a matrix named m= m = [[1, 2, 3], [4, 2, 3],[1, 5, 3],[4, 2, 6]] we need to count the most common element in each column in the matrix we so that the output in this case will be [1,2,3]. We can do this by using multiple function like Counter from colleciton library and defaultdict.
Using collections.Counter and zip
This is the method we discussed earlier, which uses zip to transpose the matrix and Counter to count frequencies.
Python
from collections import Counter
m = [
[1, 2, 3],
[4, 2, 3],
[1, 5, 3],
[4, 2, 6]
]
# Transpose the matrix to get columns as rows
a = zip(*m)
# Find the most common element in each column
b = [Counter(col).most_common(1)[0][0] for col in a]
print("Most common elements in each column:", b)
OutputMost common elements in each column: [1, 2, 3]
Explanation:
- zip(*matrix): Transposes the matrix to group the columns as rows.
- Counter(col).most_common(1)[0][0]: Finds the most common element in each column and extracts it.
Using defaultdict from collections
Using defaultdict to count occurrences manually without directly using Counter
Python
from collections import defaultdict
m = [
[1, 2, 3],
[4, 2, 3],
[1, 5, 3],
[4, 2, 6]
]
# Transpose the matrix to get columns as rows
a = zip(*m)
# Find the most common element in each column
c = []
for col in a:
frq = defaultdict(int)
# Count occurrences of each element
for element in col:
frq[element] += 1
# Find the element with the maximum count
c.append(max(frq, key=frq.get))
print("Most common elements in each column:", c)
OutputMost common elements in each column: [1, 2, 3]
Explanation:
- defaultdict(int): Initializes a dictionary where missing values default to 0, making it easier to count occurrences.
- max(frq, key=frq.get): Finds the key (element) with the highest frequency in each column.
Using pandas
If we're working with large datasets or prefer a simpler approach, we can use pandas.
Python
import pandas as pd
m = [
[1, 2, 3],
[4, 2, 3],
[1, 5, 3],
[4, 2, 6]
]
# Convert the matrix into a DataFrame
df = pd.DataFrame(m)
# Find the most common element in each column
c = df.mode().iloc[0].tolist()
print("Most common elements in each column:", c)
OutputMost common elements in each column: [1.0, 2.0, 3.0]
Explanation:
- pd.DataFrame(matrix): Converts the 2D list into a DataFrame.
- df.mode(): Finds the most frequent value in each column.
- .iloc[0].tolist(): Retrieves the first row (since mode() returns the most frequent values, and .iloc[0] gets the first occurrence of each mode).
Similar Reads
Python | Find most common element in a 2D list Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list. Examples: Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]] Output : 10 Input : [['geeks', 'wins'], ['techie', 'wins']] Output : wins Approach #1 : Using max() function F
5 min read
Python | Find common elements in list of lists The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
6 min read
Python | Find most frequent element in a list Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python.ExampleMake a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we f
2 min read
Python | Check if two lists have any element in common Checking if two lists share any common elements is a frequent requirement in Python. It can be efficiently handled using different methods depending on the use case. In this article, we explore some simple and effective ways to perform this check.Using set IntersectionSet intersection uses Python's
3 min read
Python - Print all common elements of two lists Finding common elements between two lists is a common operation in Python, especially in data comparison tasks. Python provides multiple ways to achieve this, from basic loops to set operations. Let's see how we can print all the common elements of two listsUsing Set Intersection (Most Efficient)The
3 min read