function outputs the number of all unique values in a column, for example

 apple   3
 orange  2
 banana  1

I want to search the total number of (value = 'apple') only, which function can replace value_counts()?

  • $\begingroup$ Hi! It would have helped me if you would provide the declaration of your data structure. I think your series is actually a column in a dataframe, but you'll manage. $\endgroup$ Aug 13 '19 at 11:16

You have plenty of ways to do it. You won't see a big difference in performance. My suggestion is to use whatever feels more convenient for you or your team.

import pandas as pd
import numpy as np

#Let's create a dataframe with 10 million integers from 0 to 100
df = pd.DataFrame(np.random.randint(0,100,size=(10000000, 1)), columns=list('A'))

#And now count the value 5 with 4 different ways

%timeit df[df.A == 5].shape[0]
10 loops, best of 3: 25.4 ms per loop

%timeit len(df[df.A == 5])
10 loops, best of 3: 25.4 ms per loop

%timeit len(df[df.A == 5].index)
10 loops, best of 3: 25.6 ms per loop

%timeit df['A'].value_counts()[5]
10 loops, best of 3: 149 ms per loop

As you can see, only the last one takes more time to run.

EDIT: Addition to your comment, you could try this

df = data.groupby('a_1').get_group(a_2)['suffix']
len(df[df.suffix == 'a_3'])
  • $\begingroup$ i changed my code to data.groupby('a_1').get_group(a_2)['suffix'].value_counts()['a_3'], it works. i tried to changed to other 3 faster functions. how? $\endgroup$
    – TJCLK
    Aug 14 '19 at 2:22
  • 1
    $\begingroup$ @LiDong please check my edit $\endgroup$
    – Tasos
    Aug 14 '19 at 5:47

You can filter a Series, then apply the value_count.


fruits[fruits == "apple"].value_counts()
  • 1
    $\begingroup$ Instead of using value_counts() you can just use len() function on the filtered result $\endgroup$
    – vico
    Aug 13 '19 at 11:47
  • $\begingroup$ Yes you are right. $\endgroup$ Aug 13 '19 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.