What i want is including zero counts categories while generating frequencies for categorical variables


col1   col2 
a       x
c       y
a       y
f       z

what i want is to generate a frequency table with counts and percentages including zero counts categories


  Counts   Cercentage
a  2          50.0%
b  0          0.0%
c  1          25.0%
d  0          0.0%
e  1          25.0%

what i have done is generating the frequency table with counts and percentages but i need to include also the zero counts categories like b and d as illustrated above

here is what i have tried

                                dropna=False).mul(100).round(1).astype(str) + '%'],

any help please

  • $\begingroup$ Hello there, could you please try to use Code blocks so your tables look cleaner, and give a clear example of what you try to do ? I can't understand the question... $\endgroup$ – BeamsAdept Sep 23 '20 at 9:50

I got the answer use of Series.reindex with a list of all categories and if not match replace to 0

  categories = ['a', 'b', 'c', 'd', 'e']
  pd.concat([df.col1.value_counts().reindex(categories[::-1], fill_value=0),        df.col1.value_counts(normalize=True).reindex(categories[::-1], fill_value=0).mul(100).round(1).astype(str) + '%'],axis=1, keys=('Counts','Percentage'))

This worked for me

  • $\begingroup$ Welcome to DS SE! If you answered your own question, would you please mark it as such? Click the checkmark under the vote buttons on your answer. $\endgroup$ – Benji Albert Sep 23 '20 at 14:30

I couldn't understand the question, but if I only consider the title "including empty categories with pandas value_counts()" here's the way to do it :

  • $\begingroup$ sorry maybe that was not well state but i want is to include zero counts $\endgroup$ – Espoir Sep 23 '20 at 10:01

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.