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()?
Data Science Stack Exchange is a question and answer site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field. It only takes a minute to sign up.Sign up to join this community
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 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() 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'])