TheUndecided
TheUndecided

Reputation: 187

Counter when 2 values are most frequent

For example, I got a list of lists with two values which are tied in being the most frequent. Lines = the list of lists, I used:

from collections import Counter
most_freq = Counter(bin for sublist in lines for bin in sublist).most_common(1)[0][0]

Iterating over the list, it prints only one result (I understand that's because of the 1).. I found recently in the forum the following code:

counts = collections.Counter(lines)
mostCommon = counts.most_common()
print(mostCommon)

But the error is "TypeError: unhashable type: 'list'" What should I change to print all most frequent values available?

Upvotes: 1

Views: 1133

Answers (3)

TheUndecided
TheUndecided

Reputation: 187

Possible adding:

most = Counter(b for sublist in lines for b in sublist).most_common(1)[0][0] # most freq'
all_freq = Counter(g for sublist in lines for g in sublist).most_common() 
# prints all frequencies
how_many_times_most_appears = Counter(b for sublist in lines for b in sublist).most_common(1)[0][1] # The most frequent
for k in all_freq:
    if k[1] == how_many_times_most_appears:
        print(k)
 
 # finding which value is same as the most

Upvotes: 0

Jasmijn
Jasmijn

Reputation: 10452

This prints a list of the two most common items in the sublists:

from collections import Counter
most_common = Counter(item for sublist in lines for item in sublist).most_common(2)
print([item for item, _ in most_common])

After your comment, I think you are looking for the multimode:

from statistics import multimode
print(multimode(item for sublist in lines for item in sublist))

Upvotes: 1

Vasilis G.
Vasilis G.

Reputation: 7846

You can use the count() method from the list, in order to find the total occurences of each sublist and then use the max function to find the most frequent one:

most_common = max(lines, key=lambda e: lines.count(e))

Upvotes: 0

Related Questions