0

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

jayden
  • 21
  • 2

2 Answers2

0

Try this:

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

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

results['dog']
2
0

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})
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36