Python Practice › Pandas Programs › Program 52

Population per country

EasyPandas Programs · 52 of 95

Write a pandas program to total the population per country from a data set.

Advertisement
Output
country
China    46700000
India    40300000
USA        980000
Name: population, dtype: int64

Approach

  1. groupby("country")["population"].sum().

Solution

Python
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
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs