I saw a couple of related questions (1, 2, 3), but they don't produce the output that I'm looking for. I have a dataframe like this:
df = pd.DataFrame({'Country': ['USA','USA','Canada','Canada'],
'City': ['Los Angeles','NYC','Toronto','Toronto'],
'Value': [100,200,300,400]})
df
country city value
0 USA Los Angeles 100
1 USA NYC 200
2 Canada Toronto 300
3 Canada Toronto 400
And I want to count the number of unique cities for each country. I'm currently doing this:
df.groupby('country').city.unique().apply(len)
Country
Canada 1
USA 2
Is this a reasonable way, or is there something better? Thank you.