1
$\begingroup$
value_counts()

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()?

$\endgroup$
1
  • $\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, 2019 at 11:16

2 Answers 2

4
$\begingroup$

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'])
$\endgroup$
2
  • $\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, 2019 at 2:22
  • 1
    $\begingroup$ @LiDong please check my edit $\endgroup$
    – Tasos
    Aug 14, 2019 at 5:47
1
$\begingroup$

You can filter a Series, then apply the value_count.

eg:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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