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:
{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}