1

I'm trying to get the number of the two elements that are the most frequent in an array. For example, in the list ['aa','bb','cc','dd','bb','bb','cc','ff'] the number of the most frequent should be 3(the number of times 'bb' appear in the array) and the second most frequent 2(number of times 'cc' appear in the array).

I tried this:

max = 0
snd_max = 0
for i in x:
 aux=x.count(i)
 if aux > max
   snd_max=max
   max=aux

print(max, snd_max)

But I was in doubt if there is an easier way?

Asocia
  • 5,935
  • 2
  • 21
  • 46
one user
  • 109
  • 9

4 Answers4

8

You can use collections.Counter:

from collections import Counter
x = ['aa','bb','cc','dd','bb','bb','cc','ff']
counter = Counter(x)
print(counter.most_common(2))
[('bb', 3), ('cc', 2)]
Asocia
  • 5,935
  • 2
  • 21
  • 46
1

Try this:

l = ['aa','bb','cc','dd','bb','bb','cc','ff']
b = list(dict.fromkeys(l))
a = [(l.count(x), x) for x in b]
a.sort(reverse=True)
a = a[:2]
print(a)
Sergio García
  • 486
  • 5
  • 15
1

I use max(), it's simple.

lst = ['aa','bb','cc','dd','bb','bb','cc','ff']
print(max(set(lst), key=lst.count))
Dav_Did
  • 188
  • 10
0

You could use pandas value_counts()

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html

Put the list into the dataframe, then use value counts.

That will give you a dataframe with each element and and how many times it appears, sorted by the most common on top.