Python Practice › Pandas Programs › Program 52
Population per country
Write a pandas program to total the population per country from a data set.
Output
country China 46700000 India 40300000 USA 980000 Name: population, dtype: int64
Approach
groupby("country")["population"].sum().
Solution
import pandas as pddata = pd.DataFrame({ "country": ["India", "China", "India", "USA", "China"], "city": ["Pune", "Shanghai", "Delhi", "Austin", "Beijing"], "population": [7_400_000, 24_900_000, 32_900_000, 980_000, 21_800_000],})print(data.groupby("country")["population"].sum().sort_values(ascending=False))Output
country China 46700000 India 40300000 USA 980000 Name: population, dtype: int64
Learn the concept
New to this topic? Read the lesson, then come back.