Pulse Data Hub

Pandas Cheat Sheet: 10 Operations, Tested on Real Data

This pandas cheat sheet covers the ten operations you use every day: inspecting, filtering, adding columns, grouping, pivoting, merging, ranking, reshaping, rolling averages and gap checks. Every snippet was run on one real table, 274 rows of health spending and life expectancy for six countries, and the printed output is what pandas returned.

The data is the healthexp sample from the seaborn data repository (Year, Country, Spending_USD, Life_Expectancy), loaded straight from GitHub. It was run with pandas 3.0.5. Each section ends with a gotcha, because most pandas bugs come from the data, not the syntax.

Line chart of life expectancy for six countries from 1970 to 2020; Japan ends highest at 84.7 years and the USA, drawn in red, ends lowest at 77.0 after a drop in 2020.
Life expectancy by country from the table used in this cheat sheet. Lines join the years that exist; several countries have gaps.

1. Load and inspect

import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/healthexp.csv"
df = pd.read_csv(url)
print(df.shape)
print(df.dtypes.to_string())
print(df.describe().round(1).to_string())
(274, 4)
Year                 int64
Country                str
Spending_USD       float64
Life_Expectancy    float64
         Year  Spending_USD  Life_Expectancy
count   274.0         274.0            274.0
mean   1997.0        2789.3             77.9
std      14.2        2194.9              3.3
min    1970.0         124.0             70.6
25%    1985.2        1038.4             75.5
50%    1998.0        2295.6             78.1
75%    2009.0        4055.6             80.6
max    2020.0       11859.2             84.7

Always run shape, dtypes and describe() first. Note that in pandas 3 text columns show as str, not object. Gotcha: 6 countries over 51 years would be 306 rows, but the table has 274, so 32 country-years are missing. We find them in section 10. For a longer routine, see our guide to exploratory data analysis in Python.

2. Select and filter rows

print(df[(df.Country == "USA") & (df.Year >= 2018)])
print(df.query("Year == 2020 and Spending_USD > 5000")[["Country", "Spending_USD"]])
     Year Country  Spending_USD  Life_Expectancy
261  2018     USA     10451.386             78.7
267  2019     USA     10855.517             78.8
273  2020     USA     11859.179             77.0
           Country  Spending_USD
268         Canada      5828.324
269        Germany      6938.983
270         France      5468.418
271  Great Britain      5018.700
273            USA     11859.179

Use & and | with parentheses around each condition, or use query() for readable strings. Gotcha: and and or raise an error on a boolean Series.

3. Add columns

df["Spend_k"] = (df.Spending_USD / 1000).round(2)
df["LE_gain"] = df.sort_values("Year").groupby("Country").Life_Expectancy.diff()
print(df[df.Country == "Japan"].tail(3).to_string())
     Year Country  Spending_USD  Life_Expectancy  Spend_k  LE_gain
260  2018   Japan      4554.276             84.3     4.55      0.1
266  2019   Japan      4610.794             84.4     4.61      0.1
272  2020   Japan      4665.641             84.7     4.67      0.3

Group first and then call diff(), otherwise the first year of one country is subtracted from the last year of the previous one. Gotcha: diff() works on the previous row, so sort by time first. If a country has missing years, as France does, the difference spans several years.

4. Group and aggregate

g = df.groupby("Country").agg(first=("Year", "min"), last=("Year", "max"),
                              le_mean=("Life_Expectancy", "mean"),
                              spend_max=("Spending_USD", "max")).round(1)
print(g.to_string())
print(df.groupby("Country").size().to_string())
               first  last  le_mean  spend_max
Country                                       
Canada          1971  2020     78.7     5828.3
France          1970  2020     79.6     5468.4
Germany         1970  2020     76.7     6939.0
Great Britain   1970  2020     77.6     5018.7
Japan           1970  2020     79.6     4665.6
USA             1970  2020     75.8    11859.2
Country
Canada           44
France           35
Germany          50
Great Britain    43
Japan            51
USA              51

Named aggregation, name=(column, function), gives readable column names. The row counts already expose the missing years: only Japan and the USA have all 51. Gotcha: an average over different year ranges is not comparable, because Canada starts in 1971 and the means include different decades.

5. Pivot to a wide table

w = df.pivot(index="Year", columns="Country", values="Life_Expectancy")
print(w.loc[[1970, 1990, 2010, 2020]].to_string())
print(w.shape, w.isna().sum().sum())
Country  Canada  France  Germany  Great Britain  Japan   USA
Year                                                        
1970        NaN    72.2     70.6           71.9   72.0  70.9
1990       77.3    77.0     77.3           75.7   78.9  75.3
2010       81.2    81.8     80.5           80.6   82.9  78.6
2020       81.7    82.3     81.1           80.4   84.7  77.0
(51, 6) 32

A pivot makes the missing rows visible: 51 years by 6 countries is 306 cells, and 32 are empty. Gotcha: pivot() fails if an index and column pair repeats. Use pivot_table() with an aggregation in that case. Here there are no duplicates, which we check in section 10.

6. Compare first and last values

print((w.loc[2020] - w.loc[1970]).sort_values(ascending=False).round(1).to_string())
Country
Japan            12.7
Germany          10.5
France           10.1
Great Britain     8.5
USA               6.1
Canada            NaN

Canada comes out as NaN because 1970 is empty for it. Taking each country’s first and last recorded value instead gives Canada a gain of 8.9 years, measured from 1971. The USA gained the least, 6.1 years, while spending the most. Gotcha: arithmetic with NaN returns NaN without warning, so a missing cell silently drops a row from a ranking.

7. Merge two tables

reg = pd.DataFrame({"Country": ["USA", "Canada", "Japan", "France", "Germany"],
                    "Region": ["North America", "North America", "Asia", "Europe", "Europe"]})
m = df.merge(reg, on="Country", how="left")
print(m.Region.isna().sum(), m[m.Region.isna()].Country.unique().tolist())
print(len(df.merge(reg, on="Country", how="inner")))
print(m.groupby("Region", dropna=False).Life_Expectancy.mean().round(1).to_string())
43 ['Great Britain']
231
Region
Asia             79.6
Europe           77.9
North America    77.2
NaN              77.6

We left Great Britain out of the lookup table on purpose, and the merge shows the cost. A left join keeps all 274 rows and leaves 43 with no region. An inner join keeps only 231 and silently drops Great Britain. Always count rows before and after a merge. Gotcha: groupby drops NaN keys unless you pass dropna=False. The same joins in SQL are covered in SQL for data analysis.

8. Rank within groups

df["rank_spend"] = df.groupby("Year").Spending_USD.rank(ascending=False)
usa = df[df.Country == "USA"]
print((usa.rank_spend == 1).sum(), "of", len(usa))
51 of 51

The USA ranked first in spending in all 51 years, rising from $327 per person in 1970 to $11,859 in 2020. Yet its life expectancy fell from 78.8 in 2019 to 77.0 in 2020, a drop of 1.8 years, against smaller changes elsewhere (Great Britain -1.0, Japan +0.3). The table cannot say why. The year 2020 was the start of the COVID-19 pandemic, which is outside knowledge, not something in this file. Gotcha: rank() gives ties an average rank unless you set method.

9. Reshape back to long format

long = w.reset_index().melt(id_vars="Year", var_name="Country", value_name="LE").dropna()
print(long.shape)
(274, 3)

melt() reverses a pivot. After dropping the 32 empty cells we are back at exactly 274 rows, which confirms nothing was lost in the round trip. Long format is what plotting libraries and groupby prefer, as we show in data visualization with Matplotlib. Gotcha: forget dropna() and the empty cells come back as rows.

10. Check duplicates and gaps

print(df.duplicated(["Country", "Year"]).sum())
print(w.isna().sum().to_dict())
print(w.index[w.Canada.isna()].tolist())
us = w["USA"]
print(us.rolling(5).mean().round(2).tail(3).to_string())
0
{'Canada': 7, 'France': 16, 'Germany': 1, 'Great Britain': 8, 'Japan': 0, 'USA': 0}
[1970, 1972, 1973, 1974, 1975, 1977, 1978]
Year
2018    78.72
2019    78.70
2020    78.36

No duplicate country-year pairs, so pivot() was safe. The gaps are not random: France has a value only every fifth year until 1990 (16 years missing), and Canada is missing 7 years in the 1970s. A rolling mean is the last tool here, and it suits a complete series like the USA’s, where the 5-year average smooths 2020 to 78.36. Gotcha: on a series with gaps, a rolling window counts rows, not years, so it can span far more time than you expect. Fix the calendar first, for example with reindex. For a broader cleaning routine, read how to clean and preprocess data in Python.

Where to go next

For a longer walk through selecting, grouping and merging, see data manipulation with pandas. The official pandas user guide documents every function used above, and the data comes from the seaborn-data repository.

FAQ

What is the difference between pivot and pivot_table in pandas?

pivot() only reshapes and raises an error if a row and column pair appears twice. pivot_table() aggregates duplicates with a function such as the mean.

Should I use a left or an inner merge?

Use a left join when you must keep every row of the main table, and check for NaN afterwards. In our test, the inner join dropped 43 of 274 rows without any warning.

Why does my groupby result lose rows?

By default groupby drops rows whose key is NaN. Pass dropna=False to keep them, as in section 7.

How do I find missing years in a time series?

Pivot the table so each year is a row, then count NaN per column, as in section 10. Pivoting is the fastest way to turn absent rows into visible empty cells.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights