How to make a list of values based on value count in pandas

Viewed 4368

I have a dataframe like this

   name
    a
    s
    d
    a
    s
    d
    f
    a
    s
    a
    s

I need to finally get the top 3 values based on value count.I did got value counts. I used,data2['name'].value_counts(sort=True,ascending=False). But instead of value count, I need those top 3 name values. ie,

[a,s,d]
2 Answers

Function Series.value_counts has default parameters sort=True and ascending=False, so should be omitted. Then filter index values by indexing and convert to list:

L = data2['name'].value_counts().index[:3].tolist()
print (L)
['a', 's', 'd']

Another solution:

from collections import Counter
L = [i for i, j in Counter(data2['name']).most_common(3)]
print (L)
['a', 's', 'd']

You can also use Series.nlargest, so sorting arguments won't matter:

data2['name'].value_counts().nlargest(3).index
Related