Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the number of times an element appered in entire dataframe?

I have a Pandas DataFrame like this:

pd.DataFrame({'names_1' : ['cat', 'dog', 'elephant'],
              'names_2' : ['rat', 'cat', 'tiger'],
              'names_3' : ['cow', 'monkey', 'cat']})


# Output -

    names_1     names_2    names_3
0   cat         rat        cow
1   dog         cat        monkey
2   elephant    tiger      cat

I want to count the number of time 'cat' appeared in the entire dataset. I know about value_counts() method, but it only counts the element in a specific column. How do I count cat appearance in the entire dataset?

Edit – In my use case, I want to return a dictionary of counts of each element, like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{cat:3, dog:1, elephant:1, etc..}

>Solution :

df = pd.DataFrame({'names_1' : ['cat', 'dog', 'elephant'],
                  'names_2' : ['rat', 'cat', 'tiger'],
                  'names_3' : ['cow', 'monkey', 'cat']})
    
occurence = df.stack().value_counts().to_dict()

results in

{'cat': 3, 'rat': 1, 'cow': 1, 'dog': 1, 'monkey': 1, 'elephant': 1, 'tiger': 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading