Use a single-line command to find the cardinality of all the values within a column within a dataframe

Viewed 23

how would I use a single-line command to find the cardinality of all the values within a column within a dataframe? Using only pandas. I have a column of data made up of different strings and I want to count the number of occurrences of each value within that column. Example

df = pd.DataFrame({'Animal':['cat', 'dog', 'bird', 'dog', 'bird', 'bird']})

How would get the cardinality of each string?

cat : 1 bird : 3 dog: 2

so that I could also us it to make a bar plot using pandas

2 Answers

Try this:

results = df['Animal'].value_counts()

If you want to call the value of a specific animal, just:

results['dog']
2

There is a built-in Python collection for this, the Counter:

from collections import Counter
print(Counter(['cat', 'dog', 'bird', 'dog', 'bird', 'bird']))
# Counter({'bird': 3, 'dog': 2, 'cat': 1})
Related