Hierarchical clustering with Ward’s method in Python
How distance and linkage shape a cluster analysis, from preparing World Happiness Report data to interpreting a dendrogram and plotting clusters in Python.
Jan Kirenz · · 15 min read
This tutorial introduces cluster analysis and applies Ward’s method in Python to group countries by healthy life expectancy and GDP per capita.
Cluster analysis
Cluster analysis is an exploratory method for finding patterns of similarity in data.
The objects in a cluster analysis can be people, products, films, countries or companies. Clustering groups them by the values of their features. The aim is to make the members of each cluster as similar to one another as possible (homogeneity) while keeping different clusters as distinct as possible (heterogeneity).
Netflix, for example, recorded subscribers’ viewing habits and used them to identify more than 2,000 small clusters called “taste communities”. Membership of a community helped Netflix recommend titles that matched a subscriber’s interests. Films can also be grouped by their features and the resulting clusters given descriptive names, as the figure illustrates. New York Magazine, 2018, Netflix, 2017

Several prerequisites are worth checking before running a cluster analysis. University of Zurich, 2018
- Clustering can be applied to different types of data, including categorical and numerical variables.
- Missing values and outliers should be addressed before clustering.
- If variables cover very different ranges, for example because one is measured in centimetres and another in kilometres, put them on a common scale. A common approach is z-score standardisation.
A clustering algorithm follows rules to decide which observations belong together. The resulting groups depend both on these rules and on how distance or similarity between observations is measured.
The first step is therefore to choose a proximity measure that suits the types of data in the analysis.
Proximity measures
A proximity measure describes how close two observations are. Depending on the measurement scale of the variables, a distance function measures how far apart the observations are, or a similarity function measures how alike they are.
-
Similarity measures can be used for categorical variables, whether nominal or ordinal.
-
Distance measures are commonly used for numerical variables measured on a metric scale.
This tutorial covers Euclidean distance (L2 distance), squared Euclidean distance and L1 distance. The last of these is also called Manhattan, Mannheim, taxicab or city-block distance.
Euclidean distance
Euclidean distance is the straight-line distance between two points. On a sheet of paper, it is the length a ruler would measure along the line segment connecting them. A distance of zero means the points coincide on all the variables used in the calculation.
For points A and B described by n variables, Euclidean distance is given by
d(A, B) = √( Σi=1n ( Ai − Bi )² )
With two variables, X and Y (n = 2), the distance can be drawn in a two-dimensional coordinate system. Korstanje, 2019

The scatter plot gives the following coordinates for points A and B.
- xA = 70
- xB = 330
- yA = 40
- yB = 228
In two dimensions (n = 2), the formula for Euclidean distance is the Pythagorean theorem. The differences in the X and Y coordinates give the lengths of the two shorter sides of a right triangle. The distance between A and B is the length of its hypotenuse.
d(A, B) = √( ( xA − xB )² + ( yA − yB )² )
d(A, B) = √( (70 − 330)² + (40 − 228)² )
d(A, B) = √( (−260)² + (−188)² )
d(A, B) = √( 67 600 + 35 344 )
d(A, B) = √( 102 944 )
d(A, B) ≈ 320.85
Squared Euclidean distance
Squaring Euclidean distance gives greater weight to larger differences. The squared distance is
d²(A, B) = Σi=1n ( Ai − Bi )²
For the same two points, this gives
d²(A, B) = ( xA − xB )² + ( yA − yB )²
d²(A, B) = (70 − 330)² + (40 − 228)²
d²(A, B) = 102 944
L1 distance
L1 distance is the sum of the absolute differences between corresponding coordinates of two points A and B. It is also known as Manhattan, Mannheim, taxicab or city-block distance. It is useful for describing travel along a grid of streets, as in Manhattan or Mannheim, where the direct diagonal route is unavailable. Korstanje, 2019

Several routes connect A and B in the diagram. Each follows the streets. For example, travelling two blocks north and then three blocks east reaches B from A. Changing the order of those moves gives another shortest route of exactly the same length.
The general formula for L1 distance is
d(A, B) = Σi | Ai − Bi |
For points A and B, the calculation is
d(A, B) = | xA − xB | + | yA − yB |
d(A, B) = | 70 − 330 | + | 40 − 228 |
d(A, B) = | −260 | + | −188 |
d(A, B) = 260 + 188
d(A, B) = 448
Clustering algorithms
Once the proximity measure has been calculated, a clustering algorithm groups the observations. The figure shows several families of algorithms. University of Zurich, 2018

The figure distinguishes between hierarchical and non-hierarchical algorithms. This tutorial focuses on hierarchical methods, which can be either agglomerative or divisive.
A divisive method starts with all observations in one cluster. It splits the cluster repeatedly until each observation forms a cluster of its own. An agglomerative method works in the opposite direction. Each observation starts in its own cluster, and successive steps merge clusters into larger groups. Agglomerative methods include the linkage methods described below and methods based on variance.
Linkage methods
At each step, a linkage method finds the two closest clusters and merges them. The choice of linkage determines how the distance between two clusters is calculated. University of Zurich, 2018
- Single linkage (nearest neighbour) uses the smallest distance between any point in the first cluster and any point in the second. Sigbert, 2011
- Complete linkage (furthest neighbour) uses the largest distance between any point in the first cluster and any point in the second. Sigbert, 2011
- Average linkage calculates the mean of all pairwise distances between points in the first cluster and points in the second. Sigbert, 2011
- Median linkage measures the Euclidean distance between cluster centres. When two clusters merge, the new centre is halfway between their previous centres. Each contributes equally, regardless of how many observations it contains. SciPy linkage documentation
Ward’s method
Another widely used agglomerative method is Ward’s method, which is based on variance. It merges the pair of clusters that produces the smallest increase in total within-cluster variation. This extends the idea of the empirical variance of a single variable to several variables.
The empirical variance of one variable is
s² = (1/n) Σi=1n ( xi − x̄ )²
For a dataset with p variables Xj, total variance is
T = (1/n) Σj=1p Σi=1n ( xij − x̄j )²
In the first formula, (xi − x̄)² is the squared Euclidean distance d²(xi, x̄). For each cluster, the method sums the squared distances of its observations from that cluster’s mean across all p variables. At the next step it merges the two clusters that cause the smallest increase in the total within-cluster sum of squares.
The figure compares the clusters produced by several algorithms on a range of datasets. scikit-learn

In some of these examples, single linkage produces clusters of very different sizes. Ward’s method gives a more balanced partition in most of the examples shown. The following analysis uses Ward’s method.
Cluster analysis in Python
The example applies hierarchical clustering with Ward’s method to the 2020 World Happiness Report. The United Nations Sustainable Development Solutions Network published the report as part of its annual series. It ranks countries by life satisfaction and examines the data from several perspectives. Helliwell et al., 2020
The first step is to import the data.
import pandas as pd
# Read the CSV file
df = pd.read_csv("https://raw.githubusercontent.com/kirenz/datasets/master/whr_20.csv")
The analysis uses two country-level variables: healthy life expectancy in years (healthy_life_expectancy) and the logarithm of gross domestic product per person (logged_gdp_per_capita).
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
sns.scatterplot(
data=df,
x="logged_gdp_per_capita", y="healthy_life_expectancy",
palette ="crest"
);
To make the clustering easier to follow, the example takes a random sample of 20 countries. Setting random_state to a fixed number, here 12, ensures that running the code again selects the same 20 countries.
df = df.sample(n=20, random_state=12)
A scatter plot shows where each country in the sample lies.
plt.figure(figsize=(6,6))
sns.set_theme(style="ticks", font_scale=1.00)
g = sns.scatterplot(
data=df,
x="logged_gdp_per_capita", y="healthy_life_expectancy", hue="country_name",
palette="crest", s=100
)
plt.title("Life satisfaction (2020)")
plt.xlabel("Log GDP per capita")
plt.ylabel("Healthy life expectancy in years")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);
Preparing the data
Selecting variables
A new data frame, df_cl, holds the two numerical variables for clustering. It also retains country_name so that the observations can be labelled later.
df_cl = df[["country_name", "logged_gdp_per_capita", "healthy_life_expectancy"]]
Missing values
The following calculation counts the missing values in each column.
df_cl.isnull().sum(axis=0)
country_name 0
logged_gdp_per_capita 0
healthy_life_expectancy 0
dtype: int64
The dataset has no missing values. If another dataset contained gaps, dropna(axis=0) would remove the affected rows. Here axis=0 refers to the rows of the data frame.
df_cl = df_cl.dropna(axis=0)
Standardisation
Z-score standardisation puts the two variables on a common scale. After the transformation, each variable has a mean of 0 and a standard deviation of 1. The formula is
z = (x − x̄) / s
- x̄ is the mean of the data.
- s is the standard deviation of the data.
The code creates a copy of the data frame called df_cl_z and uses StandardScaler() to standardise its numerical variables.
from sklearn.preprocessing import StandardScaler
df_cl_z = df_cl.copy()
features = ["logged_gdp_per_capita","healthy_life_expectancy"]
scaler = StandardScaler()
df_cl_z[features] = scaler.fit_transform(df_cl_z[features])
df_cl_z.head()
| country_name | logged_gdp_per_capita | healthy_life_expectancy | |
|---|---|---|---|
| 66 | Paraguay | 0.223408 | 0.288739 |
| 149 | Rwanda | -1.034138 | -0.304923 |
| 72 | Russia | 0.742543 | 0.087481 |
| 80 | Mongolia | 0.239009 | -0.147308 |
| 23 | Mexico | 0.509934 | 0.636364 |
The countries retain their relative positions in the scatter plot. The units on the horizontal and vertical axes have changed: they now express distance from the mean in standard deviations.
plt.figure(figsize=(6,6))
sns.set_theme(style="ticks", font_scale=1.00)
g = sns.scatterplot(
data=df_cl_z,
x="logged_gdp_per_capita", y="healthy_life_expectancy", hue="country_name",
palette="crest", s=100
)
plt.title("Life satisfaction (2020)")
plt.xlabel("Log GDP per capita (standard deviations from the mean)")
plt.ylabel("Healthy life expectancy (standard deviations from the mean)")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);
Setting country_name as the index keeps the country names available as labels and leaves only the numerical variables in the clustering calculation.
df_cl_z = df_cl_z.set_index('country_name')
df_cl_z.index.name = None
df_cl_z.head()
| logged_gdp_per_capita | healthy_life_expectancy | |
|---|---|---|
| Paraguay | 0.223408 | 0.288739 |
| Rwanda | -1.034138 | -0.304923 |
| Russia | 0.742543 | 0.087481 |
| Mongolia | 0.239009 | -0.147308 |
| Mexico | 0.509934 | 0.636364 |
Dendrogram
A dendrogram shows the sequence in which clusters merge. It helps with choosing how many clusters to retain, a decision that this algorithm leaves to the analyst.
The dendrogram in this example reads from left to right.
- The horizontal axis indicates how dissimilar the clusters are when they merge.
- The country names appear on the left.
- Each country starts as its own cluster, shown by its own horizontal line.
- Following the lines from left to right shows the clusters merging into larger groups.
- The first merge joins the two countries with the smallest distance between them.
- Each vertical line marks the merger of two clusters.
- Indonesia and Mongolia are the most similar pair in this example.
- The further to the right a merger occurs, the more dissimilar its observations or clusters are.
- At the far right, all countries belong to one cluster.
Choosing the number of clusters requires judgement. The groups should have a plausible interpretation in the context of the analysis. A large jump in the dendrogram also helps identify a possible cut. Here the largest increase in heterogeneity occurs when two clusters merge into one. There is also a substantial increase between the four-cluster and two-cluster solutions. This example retains four clusters, although two would also be a reasonable choice. There is often no single optimal solution because the interpretation of the resulting groups matters.
from scipy.cluster import hierarchy
plt.figure(figsize=(10, 7))
plt.title("Dendrogram")
Z = hierarchy.linkage(df_cl_z, 'ward')
dn = hierarchy.dendrogram(Z, labels=df_cl_z.index, orientation='right')

The next step applies hierarchical clustering with AgglomerativeClustering. The estimator uses Ward linkage and Euclidean distance. The example requests four clusters and then calls fit_predict.
from sklearn.cluster import AgglomerativeClustering
clustering = AgglomerativeClustering(linkage='ward', n_clusters=4)
clustering.fit_predict(df_cl_z)
clustering.labels_
array([0, 2, 0, 0, 0, 0, 0, 2, 0, 1, 1, 3, 0, 2, 3, 1, 1, 0, 3, 3])
The cluster labels go into df_cl, so the results can be interpreted using the variables in their original units.
df_cl["cluster"] = clustering.labels_
df_cl.head()
| country_name | logged_gdp_per_capita | healthy_life_expectancy | cluster | |
|---|---|---|---|---|
| 66 | Paraguay | 9.389982 | 65.639938 | 0 |
| 149 | Rwanda | 7.600104 | 61.098846 | 2 |
| 72 | Russia | 10.128872 | 64.100456 | 0 |
| 80 | Mongolia | 9.412187 | 62.304485 | 0 |
| 23 | Mexico | 9.797797 | 68.299026 | 0 |
The next scatter plot shows the four clusters.
- The bottom left contains countries with the lowest GDP per capita and very low healthy life expectancy.
- The top right contains countries with the highest GDP per capita and very high healthy life expectancy.
plt.figure(figsize=(6,6))
sns.set_theme(style="ticks", font_scale=1.00)
g = sns.scatterplot(
data=df_cl,
x="logged_gdp_per_capita", y="healthy_life_expectancy", hue="cluster",
palette="crest", s=100
)
plt.title("Life satisfaction (2020)")
plt.xlabel("Log GDP per capita")
plt.ylabel("Healthy life expectancy in years")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);
The same plot can show country names and cluster membership together. Colour identifies the country and marker shape identifies the cluster.
plt.figure(figsize=(8,8))
sns.set_theme(style="ticks", font_scale=1.00)
g = sns.scatterplot(
data=df_cl,
x="logged_gdp_per_capita", y="healthy_life_expectancy", hue="country_name", style="cluster",
palette="crest", s=100
)
plt.title("Life satisfaction (2020)")
plt.xlabel("Log GDP per capita")
plt.ylabel("Healthy life expectancy in years")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);
