Larry Freeman Larry Freeman - 5 months ago 14
Python Question

Using a pandas DataFrame to get the count of the 10th most frequent value

I have a DataFrame that contains entries of place_ids such as:

place_id
11111
11111
22222
33333
44444
44444
...


I would like to get the count of the 10th most frequent value.

Here's what I've come up with:

print df.place_id.value_counts().nlargest(10).tail(1).values[0]


This seems like too much work. Is there an easier way to get the count of the 10th most frequent place_id?

Answer

try:

import pandas as pd
import numpy as np
from string import ascii_letters

np.random.seed([3,1415])
s = pd.Series(np.random.choice(list(ascii_letters), (10000,)))

vc = s.value_counts().sort_values()
vc.loc[[vc.index[-10]]]

j    204
dtype: int64