You and your spouse decided to let the internet name your next child. You've asked the great people of the web to submit their favorite names, and you've compiled their submissions into a Series called babynames
.
import numpy as np
import pandas as pd
babynames = pd.Series([
'Jathonathon', 'Zeltron', 'Ruger', 'Phreddy', 'Ruger', 'Chad', 'Chad',
'Ruger', 'Ryan', 'Ruger', 'Chad', 'Ryan', 'Phreddy', 'Phreddy', 'Phreddy',
'Mister', 'Zeltron', 'Ryan', 'Ruger', 'Ruger', 'Jathonathon',
'Jathonathon', 'Ruger', 'Chad', 'Zeltron'], dtype='string')
Determine how many people voted for the names 'Chad', 'Ruger', and 'Zeltron'.
Solution¶
babynames.value_counts().loc[['Chad', 'Ruger', 'Zeltron']]
# Chad 4
# Ruger 7
# Zeltron 3
# dtype: Int64
Explanation
The trick here is to use the Series value_counts()
method to get the count of each unique element in the Series.
babynames.value_counts()
# Ruger 7
# Phreddy 4
# Chad 4
# Jathonathon 3
# Zeltron 3
# Ryan 3
# Mister 1
# dtype: Int64
This results in another Series, so we can chain it with .loc
passing in a list of the indices we want to retrieve.
babynames.value_counts().loc[['Chad', 'Ruger', 'Zeltron']]
# Chad 4
# Ruger 7
# Zeltron 3
# dtype: Int64