Open In App

Find Most Common Element in Each Column in a 2D List - Python

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
Most 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)

Output
Most 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)

Output
Most 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).

Next Article

Similar Reads