Principal components and factor analysis in Python: from 24 questions to four decisions
TL;DR
Difficulty: Advanced
Many correlated columns are usually a few things measured several times. PCA compresses behaviour, factor analysis models the opinions behind a survey.
- Clean the export first: a 0 for 'not applicable' and a few straightliners distort the correlations every later step reads.
- Count factors with parallel analysis, not Kaiser's rule alone. Read PCA loadings as components_ times the root of the eigenvalue.
- Fit the factor model with scikit learn's FactorAnalysis and varimax, check with oblimin, and name factors from anchor columns so order and sign stay fixed.
- A factor is real only if it beats noise, survives split halves and moves an outcome. Then freeze the recipe so scores stay comparable.
Twenty four survey questions or eighteen customer columns usually say four or five things. This chapter builds the Marketing Analytics chapter's principal components and factor analysis in Python, step by step, on data you generate yourself, from the raw survey export to factor scores, a regression on the outcome and a saved recipe.
Twenty four questions, four answers, now in code
Chalkline Hotels, the invented group of five small hotels in Brighton and along the Sussex coast, asks every guest 24 questions after a stay, each rated from 1 to 10. Last season 1,340 guests answered. Every average sits between 7.7 and 8.5, and Anna, who runs the group, has one question: "What do we fix first, and will it bring guests back to book direct?"
Northgate Hampers, Priya's invented gift hamper shop in Leeds, has the same problem without a survey. Her customer table has 18 behavioural columns for 6,200 customers, and most of them say the same thing in different units.
The concepts behind the answer, what principal components and factors are, why they differ and how to read them, are explained in the Marketing Analytics chapter principal components and factor analysis for marketers. Read it for the ideas. This chapter builds both analyses in Python, line by line, on data you generate yourself: the cleaning a survey export needs, standardising, the eigenvalues, parallel analysis, PCA with scikit learn, factor analysis with rotation, naming, reliability, split half stability, factor scores and the regression that turns four factors into one decision. The data is generated to resemble the example in that chapter, so the numbers you get are close to the ones you read there, not identical.
It builds on statistical models in Python with statsmodels and scikit learn, where the fit and transform pattern of scikit learn and the regression table of statsmodels are introduced. If arrays and matrix products are new to you, NumPy explained covers what you need.
If you only read one section
For the person who commissions this work and will never run the code, here is what matters.
A factor is real only if it passes three tests: noise, halves and money. It must beat what random data of the same size produces (parallel analysis). It must come back when you fit the two halves of the sample separately (split half stability). And it must move a number the business cares about. In the generated Chalkline survey, four factors pass all three: their eigenvalues sit far above the random line, the two halves agree with a congruence of 0.99 or more on every factor, and the four scores explain 48% of how likely guests are to recommend the hotel. A factor that fails any of the three is a story, not a finding. This is the single most useful idea in the chapter, and none of the three tests is the default output of any library.
Value is the biggest lever, the room is the smallest. One unit more on the Value factor adds 0.69 points to the recommendation score, one unit more on Room adds 0.44. The money Anna planned to spend on refurbishing rooms buys the least.
Clean the export before anybody factors it. Survey tools often store "not applicable" as 0. In the example, that one habit drops the correlation between breakfast and dinner from 0.57 to 0.21, and 40 guests who clicked 10 all the way down push the first eigenvalue from 7.65 to 8.39. Both are invisible in a table of averages.
Freeze the recipe. Scores are only comparable over time if next month's customers go through the same means, spreads and weights as this month's. Refitting every month quietly changes what "Gifting 1.3" means.
Ask which package versions ran it. The best known Python package for factor analysis, factor_analyzer, cannot fit a model with scikit learn 1.8 or newer as of June 2026. The analysis below uses scikit learn for the fit and borrows only the rotation helper from factor_analyzer, which still works.
Before you start: the versions this chapter uses
This chapter is written for Python 3.14 with pandas 3.0.3, NumPy 2.4.6, scikit learn 1.9.0 (released on 2 June 2026), statsmodels 0.14.6 and factor_analyzer 0.5.1, the versions current in June 2026.1 If you set up your environment as described in why Python for data analysis, and how to set it up, install them with:
pip install "pandas==3.0.3" "numpy==2.4.6" "scikit-learn==1.9.0" "statsmodels==0.14.6" "factor_analyzer==0.5.1"
Three things are worth knowing before the first line.
First, factor_analyzer's main class no longer runs. Its last release, 0.5.1, came out in February 2024. Its FactorAnalyzer.fit passes an argument called force_all_finite to a scikit learn helper, and scikit learn renamed that argument in version 1.6 and announced its removal for 1.8.2 Since scikit learn 1.8, every fit fails with TypeError: check_array() got an unexpected keyword argument 'force_all_finite'. The problem was reported in January 2026 and, at the time of writing, no fixed release is on the Python Package Index.3 Its Rotator class and its calculate_kmo function do not touch that helper and still work. So this chapter fits the factor model with scikit learn's FactorAnalysis, which supports varimax and quartimax rotation,4 and uses Rotator only for the oblique check. If you need factor_analyzer's full class, install scikit learn below 1.8 in a separate environment, and write that pin down.
Second, Wes McKinney's Python for Data Analysis, third edition, introduces scikit learn in chapter 12 and notes that, when it was written, scikit learn had no deep pandas integration.5 That has changed: since version 1.2, set_output(transform="pandas") makes transformers such as StandardScaler return a DataFrame with the original column names,6 which keeps every loading attached to the question it belongs to. The code below uses it throughout.
Third, pandas 3.0 made copy on write the only behaviour and gave text columns a dedicated string type by default.7 Nothing below depends on either, but if you adapt older code that modifies a slice in place, it will no longer change the original table.
Example: checking your versions
import sys
import numpy as np
import pandas as pd
import sklearn
import statsmodels.api as sm
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA, FactorAnalysis
print(sys.version.split()[0], pd.__version__, np.__version__, sklearn.__version__)
# 3.14 3.0.3 2.4.6 1.9.0
If your numbers differ in the last digit, nothing below changes. If scikit learn starts with 1.7 or lower, set_output and FactorAnalysis(rotation=...) still exist, so the code runs as written.
Which tool for which question
Both methods start from the same table, the correlation matrix, and both end with a few new columns that replace many old ones. They answer different questions, and the choice decides how you may read the result. The Marketing Analytics chapter explains the difference in full. In one line: PCA rewrites the data so the variance sits in the first few columns and assumes nothing about why the variables move together, while factor analysis assumes a few unseen opinions cause the answers and splits each question into a shared part and a part of its own.8
In code, the decision looks like this:
Example: two tables, two tools
Anna's three questions about the reception, problem solving and local knowledge were written to measure one thing, the service, from three angles. That is a factor analysis job. Priya's order count and total spend are different: nobody believes a hidden "spend construct" causes both. They move together because spend is orders times basket. That is a PCA job. The Chalkline survey gets factor analysis below, and Northgate gets PCA.
Step one: generate the Chalkline survey
The data follows the factor model itself. Every guest carries four hidden opinions, about service, room, food and value. Each question is a weighted mix of one opinion and noise of its own. The opinions correlate, because a guest who had a good stay tends to feel good about everything, and the room opinion is a little more independent than the rest. A WiFi question depends a little on room and service and mostly on the router. The 0 to 10 recommendation score is driven by all four opinions.
Example: 1,340 guests and 24 questions
rng = np.random.default_rng(19)
n = 1_340
# Four hidden opinions per guest: service, room, food, value.
# They correlate, because a guest who had a good stay tends to feel good about everything.
corr = np.full((4, 4), 0.46)
corr[1, :] *= 0.85
corr[:, 1] *= 0.85 # the room opinion is a little more independent
np.fill_diagonal(corr, 1.0)
opinion = rng.multivariate_normal(np.zeros(4), corr, size=n)
# Which opinion drives which question, and how strongly (the true loadings)
design = {
0: {"reception_warm": 0.78, "staff_solved_problems": 0.80, "staff_knew_area": 0.68,
"checkin_smooth": 0.74, "staff_friendly": 0.76, "requests_handled": 0.72},
1: {"room_clean": 0.84, "bed_sleep": 0.78, "bathroom": 0.79,
"room_quiet": 0.74, "room_temperature": 0.72, "room_furnishing": 0.70},
2: {"breakfast": 0.82, "dinner": 0.77, "local_produce": 0.66,
"bar_drinks": 0.70, "menu_choice": 0.72},
3: {"price_fair": 0.78, "extras_fair": 0.74, "book_direct_again": 0.66,
"value_for_money": 0.76, "rate_clear": 0.72, "offers_worth_it": 0.68},
}
latent = {}
for k, items in design.items():
for item, lam in items.items():
latent[item] = lam * opinion[:, k] + np.sqrt(1 - lam**2) * rng.standard_normal(n)
# WiFi depends a little on the room and the service, and mostly on the router
latent["wifi_speed"] = 0.36 * opinion[:, 0] + 0.38 * opinion[:, 1] + 0.82 * rng.standard_normal(n)
# Turn the hidden scores into 1 to 10 ratings
survey = pd.DataFrame({
item: np.clip(np.round(rng.uniform(7.6, 8.7) + 1.3 * x), 1, 10).astype("int64")
for item, x in latent.items()
})
# "How likely are you to recommend us?" on 0 to 10, driven by the four opinions
recommend = 8.29 + opinion @ np.array([0.48, 0.25, 0.41, 0.65]) + 1.2 * rng.standard_normal(n)
survey["recommend"] = np.clip(np.round(recommend), 0, 10).astype("int64")
survey.insert(0, "guest_id", np.arange(1, n + 1))
print(survey.shape)
print(survey.iloc[:, 1:25].mean().agg(["min", "max"]).round(2).to_dict())
# (1340, 26)
# {'min': 7.69, 'max': 8.49}
The table has one row per guest: an id, 24 ratings and the recommendation score. The averages run from 7.69 to 8.49, exactly the "everything is fine" picture Anna sees. In a real project this table is the survey tool's export, and the generation step disappears. Everything after it stays the same.
Step two: clean the export before you factor it
Factor analysis reads correlations, and two habits of survey exports quietly destroy them. The first is the code for "not applicable". Many survey tools store it as 0 (or as 99) in the same column as the real scores, so a guest who never ate dinner scores dinner at 0. The second is straightlining: a guest who clicks 10 for every question, out of politeness or to get to the end. Neither shows up as a missing value, so isna() finds nothing. Cleaning in general is covered in cleaning data in pandas. Here is what these two do to a factor analysis.
Example: what a 0 for "not applicable" and 40 straightliners do
# What a survey tool export often looks like: "not applicable" stored as 0,
# and a few guests who clicked 10 all the way down
export = survey.copy()
no_dinner = rng.random(n) < 0.22 # 22% of guests did not eat dinner
export.loc[no_dinner, "dinner"] = 0
items_raw = export.columns[1:25]
export.loc[export.index[:40], items_raw] = 10 # 40 straightliners
print(round(survey["dinner"].mean(), 2), round(export["dinner"].mean(), 2))
print(round(survey[["breakfast", "dinner"]].corr().iloc[0, 1], 2),
round(export[["breakfast", "dinner"]].corr().iloc[0, 1], 2))
top_eig = lambda frame: np.linalg.eigvalsh(frame.corr())[-1]
print(round(top_eig(survey.iloc[:, 1:25]), 2), round(top_eig(export[items_raw]), 2))
# 7.91 6.45
# 0.57 0.21
# 7.65 8.39
Read the three lines in turn. The dinner average falls from 7.91 to 6.45, which would send the kitchen into a crisis meeting about a problem that does not exist. The correlation between breakfast and dinner, the backbone of the Food factor, falls from 0.57 to 0.21, because 0 is not a low score but a different answer altogether. And 40 straightliners out of 1,340, three in a hundred, push the first eigenvalue from 7.65 to 8.39: they add a fake "everything" dimension on top of the real structure.
The fix is a short function you run on every export before anything else:
def clean_survey(raw, items):
out = raw.copy()
out[items] = out[items].replace(0, np.nan) # 0 means "not applicable", not a score
straight = out[items].std(axis=1) == 0 # identical answer to every question
print(f"not applicable answers: {int(out[items].isna().sum().sum())}, straightliners: {int(straight.sum())}")
return out.loc[~straight]
checked = clean_survey(export, items_raw)
print(checked.shape)
# not applicable answers: 257, straightliners: 40
# (1300, 26)
Two decisions are left after it, and they belong in the report. Straightliners are dropped here, which is defensible when the share is small. If it is above one guest in twenty or so, the survey is too long, and that is a finding in its own right. The 257 "not applicable" answers are now missing values, and scikit learn's FactorAnalysis refuses missing values. Either analyse the guests who answered every question, or leave a question that many guests cannot answer, like dinner at a hotel where half the guests eat out, out of the factor analysis and report it on its own. Filling it with the average invents agreement that was never there. The rest of this chapter uses the generated survey, which has neither problem.
Step three: standardise and look at the correlations
PCA and factor analysis both work on standardised variables, each column turned into "how many standard deviations above or below the average". For ratings on one scale this matters less than for behaviour, where spend in pounds would swamp a click rate. It is still the right habit, because it makes the analysis a decomposition of the correlation matrix:
Here is the rating guest gave question , is the average rating of question , its standard deviation, and the standardised value. Averages and standard deviations are explained in Foundations: spread.
Example: one guest, one question, then the matrix
Guest 1 rated reception_warm an 8. The question's average is 7.92, so with a standard deviation of about 1.3 the standardised value is : a hair above average. StandardScaler does this for every cell at once. The correlation matrix then shows the structure before any model does:
items = survey.iloc[:, 1:25] # the 24 rating questions
R = items.corr()
four = ["reception_warm", "staff_solved_problems", "room_clean", "price_fair"]
print(R.loc[four, four].round(2).to_string())
# reception_warm staff_solved_problems room_clean price_fair
# reception_warm 1.00 0.58 0.26 0.25
# staff_solved_problems 0.58 1.00 0.25 0.27
# room_clean 0.26 0.25 1.00 0.20
# price_fair 0.25 0.27 0.20 1.00
The two service questions correlate at 0.58, the cross pairs at 0.20 to 0.27. That pattern, strong inside a group and weak but positive across groups, is what factor analysis is built to find. The weak positive cross correlations matter later: they are the reason the factors themselves correlate.
Step four: is the data fit to factor at all?
The Kaiser Meyer Olkin measure (KMO) compares the ordinary correlations with the partial correlations, the correlation of two questions once every other question is held fixed. If questions share common factors, the partial correlations are small, because the other questions already explain the shared part.9
Here is the correlation of questions and , their partial correlation, and the sums run over every pair of different questions. KMO is a share of a total, see Foundations: ratios and rates. Kaiser called values in the 0.90s "marvelous", the 0.60s "mediocre" and anything below 0.50 "unacceptable".10
Example: KMO in eight lines, and the arithmetic
def kmo(data):
"""Kaiser Meyer Olkin measure: do the variables share enough to factor?"""
R = np.corrcoef(data, rowvar=False)
inv = np.linalg.inv(R)
partial = -inv / np.sqrt(np.outer(np.diag(inv), np.diag(inv))) # partial correlations
off = ~np.eye(len(R), dtype=bool) # every cell but the diagonal
r2, p2 = (R[off] ** 2).sum(), (partial[off] ** 2).sum()
return r2 / (r2 + p2)
print(round(kmo(items), 3))
# 0.94
Behind the 0.94: the squared correlations of all pairs add up to 53.91, the squared partial correlations to 3.42, so . factor_analyzer's calculate_kmo gives the same 0.940. I write it out because eight lines you understand beat an import you cannot check, and because the partial correlations come straight from the inverse of the correlation matrix, a trick worth knowing.
Step five: how many factors?
Every correlation matrix of 24 variables has 24 eigenvalues, one for each direction PCA can find, and they add up to 24. Each eigenvalue is the variance of one component, measured in "original variables": an eigenvalue of 7.65 means that direction carries as much variance as 7.65 of the questions. Three rules decide how many to keep.8 Kaiser's rule keeps every eigenvalue above one. The scree plot looks for the elbow where the eigenvalues flatten. Parallel analysis, proposed by John Horn in 1965, keeps only eigenvalues larger than random data of the same shape produces.11 In Costello and Osborne's simulations, Kaiser's rule kept too many factors in 36% of samples, and they recommend parallel analysis as accurate and easy to use.12
The share of variance a component carries is its eigenvalue divided by the total:
where is the eigenvalue of component and is the number of variables, here 24. See Foundations: ratios and rates.
Example: parallel analysis in ten lines
def parallel_analysis(n_rows, n_cols, n_sims=100, q=95, seed=1):
"""Eigenvalues that pure noise of the same shape produces, at the q-th percentile."""
g = np.random.default_rng(seed)
sims = [np.linalg.eigvalsh(np.corrcoef(g.standard_normal((n_rows, n_cols)), rowvar=False))[::-1]
for _ in range(n_sims)]
return np.percentile(sims, q, axis=0)
eig = np.linalg.eigvalsh(R)[::-1] # eigenvalues, largest first
noise = parallel_analysis(*items.shape)
print(pd.DataFrame({"survey": eig[:8], "random": noise[:8]}).round(2).T.to_string())
print("sum:", round(eig.sum(), 2), " Kaiser keeps:", int((eig > 1).sum()),
" parallel analysis keeps:", int((eig > noise).argmin()))
# 0 1 2 3 4 5 6 7
# survey 7.65 2.57 2.1 1.86 0.67 0.64 0.60 0.58
# random 1.28 1.24 1.2 1.17 1.15 1.13 1.11 1.09
# sum: 24.0 Kaiser keeps: 4 parallel analysis keeps: 4
eigvalsh returns eigenvalues smallest first, hence the [::-1]. The last line counts how many survey eigenvalues beat the random ones before the first one that does not. The first four are far above the random line, the fifth, 0.67, is far below both the random 1.15 and Kaiser's line of one. Drawn as a scree plot:
The first component alone carries of all variance, the general "it was a good stay" tendency running through every answer. The four together carry . All three rules agree on four. When they do not, keep the smaller count and say so, and let interpretability overrule them all: a factor you cannot name from its questions is not a finding. For drawing a scree plot that reads well, with the random line labelled directly instead of in a legend, see charts in Python with matplotlib, seaborn and plotly and exploring data with charts before you present anything.
Step six: PCA with scikit learn, and the loadings trap
PCA in scikit learn finds the components and stores three things you need: explained_variance_ (the eigenvalues), explained_variance_ratio_ (the shares) and components_ (the weights).4 The trap is the last one. components_ holds the eigenvectors, the weights that build each component from the standardised variables. They are not loadings. A loading is the correlation between a variable and a component, and it is the weight scaled up by the square root of the eigenvalue:
Here is the loading of variable on component , the weight from components_, and the eigenvalue of component . A loading reads like any correlation, from minus 1 to 1. Read the weights as if they were loadings and every number looks small, so nothing seems to load on anything. The square root of a variance is a standard deviation, see Foundations: spread.
Example: weights against loadings
Z = StandardScaler().set_output(transform="pandas").fit_transform(items)
pca = PCA().fit(Z)
print(pca.explained_variance_ratio_[:5].round(3), pca.explained_variance_ratio_[:4].sum().round(3))
# [0.319 0.107 0.088 0.078 0.028] 0.591
weights = pd.DataFrame(pca.components_[:4].T, index=items.columns) # the eigenvectors
pca_loadings = weights * np.sqrt(pca.explained_variance_[:4]) # weights times root of eigenvalue
print(weights.loc[["reception_warm", "room_clean"]].round(2).to_string())
print(pca_loadings.loc[["reception_warm", "room_clean"]].round(2).to_string())
# 0 1 2 3
# reception_warm 0.22 -0.07 0.31 -0.15
# room_clean 0.21 0.35 -0.07 0.01
# 0 1 2 3
# reception_warm 0.61 -0.12 0.45 -0.20
# room_clean 0.59 0.56 -0.11 0.01
As weights, reception_warm contributes 0.22 to the first component. As a loading, it correlates 0.61 with it. The unrotated components are also hard to name: both questions load about 0.6 on the first, the general tendency, and the rest is split in ways that serve variance, not meaning. That is why the next step rotates.
explained_variance_ divides by while StandardScaler divides by , so on standardised data the eigenvalues are larger than those of the correlation matrix by a factor of . That is invisible at two decimals, and worth knowing before you compare to the fourth.
Example: orders and spend, by hand and in code
The Marketing Analytics chapter works through the smallest possible case, two variables, by hand. In the generated Northgate data of step eleven, logged orders and logged spend correlate at . For a two by two correlation matrix, the eigenvalues are and , and both weights of the first component are :
- Eigenvalues: and . They add up to 2, the number of variables.
- Share of the first component: .
- Loading of each variable: .
Step eleven confirms these numbers in NumPy on the generated table. Two columns, one real dimension. With 24 or 18 columns the computer does the arithmetic, and nothing else changes.
Step seven: factor analysis with rotation
For the survey, the right model is factor analysis. scikit learn's FactorAnalysis fits it by maximum likelihood and, since version 0.24, rotates with rotation="varimax" or "quartimax".4 Varimax, introduced by Henry Kaiser in 1958, keeps the factors at right angles and pushes each question to load strongly on one factor and weakly on the rest.13 Rotation never changes how well the model fits, only how easy it is to read: any rotation of the factor axes reproduces the correlations equally well.14
The first thing to read is each question's communality, the share of its variance the factors explain:
Here is the communality of question , its loading on factor , the number of factors, and the unique variance that belongs to the question alone. Shares of variance are explained in Foundations: spread.
Example: the WiFi question drops out
fa = FactorAnalysis(n_components=4, rotation="varimax", random_state=0).fit(Z)
loadings = pd.DataFrame(fa.components_.T, index=items.columns)
communality = (loadings ** 2).sum(axis=1)
print(communality.sort_values().head(3).round(2).to_string())
# wifi_speed 0.33
# local_produce 0.42
# book_direct_again 0.43
components_ of FactorAnalysis holds the loadings directly, with no square root needed, because the factors are defined with variance one. The four factors explain only 33% of the WiFi question. It belongs to none of them, which makes sense: WiFi speed is about the router, not about how a guest was treated. I take it out of the factor solution and report it on its own, then refit on the remaining 23 questions:
items23 = items.drop(columns="wifi_speed")
Z23 = StandardScaler().set_output(transform="pandas").fit_transform(items23)
fa = FactorAnalysis(n_components=4, rotation="varimax", random_state=0).fit(Z23)
loadings = pd.DataFrame(fa.components_.T, index=items23.columns)
print(loadings.loc[["reception_warm", "room_clean", "breakfast", "price_fair"]].round(2).to_string())
# 0 1 2 3
# reception_warm -0.70 -0.16 -0.15 -0.11
# room_clean -0.14 -0.75 -0.11 -0.13
# breakfast -0.17 -0.13 -0.20 -0.72
# price_fair -0.19 -0.12 -0.73 -0.14
Look at the signs. Every loading is negative. Nothing is wrong: the sign of a factor is arbitrary, because flipping a factor and all its loadings fits exactly as well. And the order is arbitrary too: breakfast landed on the fourth factor and price on the third. If you copy these columns into a report as "factor 1 to 4", the next refit can swap them, flip them, or both, and a dashboard that showed "Value 0.8" yesterday shows "Value minus 0.8" today.
Example: naming factors from anchor questions
The fix is to choose one anchor question per factor before you look, the question that most clearly measures it. Then let the code find each anchor's factor, turn the sign so that agreeing with the anchor means a high score, and name the column:
# Name each factor after an anchor question you chose BEFORE looking,
# and turn the sign so that agreeing with the anchor means a high score
anchors = {"reception_warm": "service", "room_clean": "room",
"breakfast": "food", "price_fair": "value"}
def name_factors(loadings, anchors):
order, signs = [], []
for item in anchors:
k = loadings.loc[item].abs().idxmax()
order.append(k)
signs.append(np.sign(loadings.loc[item, k]))
assert len(set(order)) == len(order), "two anchors share a factor"
named = loadings[order] * signs
named.columns = list(anchors.values())
return named, order, np.array(signs)
named, order, signs = name_factors(loadings, anchors)
show = ["reception_warm", "staff_solved_problems", "staff_knew_area", "room_clean", "bed_sleep",
"bathroom", "breakfast", "dinner", "local_produce", "price_fair", "extras_fair", "book_direct_again"]
print(named.loc[show].round(2).to_string())
print("share of variance:", ((named ** 2).sum() / len(named)).round(3).to_dict())
The assertion is the safety net: if two anchors land on the same factor, the solution does not have the structure you expected, and the code stops instead of naming nonsense. Twelve of the 23 rows (the other 11 follow the same pattern):
| Question | Service | Room | Food | Value |
|---|---|---|---|---|
| Reception was warm and welcoming | 0.70 | 0.16 | 0.11 | 0.15 |
| Staff solved problems quickly | 0.74 | 0.15 | 0.17 | 0.13 |
| Staff knew the area well | 0.61 | 0.11 | 0.11 | 0.19 |
| Room was clean on arrival | 0.14 | 0.75 | 0.13 | 0.11 |
| Bed and sleep quality | 0.15 | 0.72 | 0.10 | 0.14 |
| Bathroom condition | 0.12 | 0.75 | 0.10 | 0.08 |
| Breakfast quality | 0.17 | 0.13 | 0.72 | 0.20 |
| Dinner quality | 0.16 | 0.13 | 0.68 | 0.18 |
| Local Sussex produce on the menu | 0.15 | 0.12 | 0.60 | 0.14 |
| Price felt fair for what we received | 0.19 | 0.12 | 0.14 | 0.73 |
| Extras were fairly priced | 0.14 | 0.12 | 0.15 | 0.71 |
| Would book direct again at this price | 0.15 | 0.15 | 0.13 | 0.60 |
Read it row by row. The service questions load 0.61 to 0.74 on the first column and no more than 0.19 elsewhere. The room questions load 0.72 to 0.75 on the second. Food and Value follow. "Local Sussex produce" is the weakest food question at 0.60, partly about food and partly about whether a guest cares about local produce at all. The shares of variance printed are 13.9% for Service, 14.3% for Room, 10.5% for Food and 13.1% for Value, together 51.8%: in factor analysis this is the shared variance only, which is why it is smaller than the 59.1% the four principal components carried.
The names are hypotheses about why the questions group, not measurements. The Marketing Analytics chapter calls this the naming fallacy, and the anchor dictionary is a small defence: it records what you expected before you saw the result.
Example: one communality by hand
reception_warm loads 0.70, 0.16, 0.11 and 0.15 on the four factors, so its communality is
and its unique variance . The four factors explain 55% of how guests rate the reception. The rest belongs to the question: the particular receptionist on the particular evening, and noise.
Step eight: check the story with an oblique rotation
Varimax forces the factors to be uncorrelated. In a survey they rarely are: a guest who felt well served also tends to feel the price was fair. An oblique rotation such as oblimin lets the factors correlate. Costello and Osborne recommend oblique rotation by default, because it gives the orthogonal answer when the factors really are uncorrelated and keeps the information when they are not.12 scikit learn has no oblique rotation, so this step borrows factor_analyzer's Rotator, the part of the package that still works. It rotates any loading matrix you hand it and reports the factor correlations in phi_.
Example: oblimin on the unrotated loadings
from factor_analyzer.rotator import Rotator
unrotated = FactorAnalysis(n_components=4, random_state=0).fit(Z23).components_.T
rot = Rotator(method="oblimin")
pattern = pd.DataFrame(rot.fit_transform(unrotated), index=items23.columns)
obl, o_order, o_signs = name_factors(pattern, anchors)
phi = pd.DataFrame(rot.phi_, index=range(4), columns=range(4)).loc[o_order, o_order]
phi = phi * np.outer(o_signs, o_signs)
phi.index = phi.columns = list(anchors.values())
print(phi.round(2).to_string())
print(obl.loc[["reception_warm", "room_clean", "breakfast", "price_fair"]].round(2).to_string())
# service room food value
# service 1.00 0.41 0.47 0.46
# room 0.41 1.00 0.37 0.36
# food 0.47 0.37 1.00 0.47
# value 0.46 0.36 0.47 1.00
# service room food value
# reception_warm 0.75 0.02 -0.04 0.00
# room_clean -0.01 0.78 0.03 -0.01
# breakfast -0.02 -0.01 0.77 0.04
# price_fair 0.03 -0.01 -0.01 0.77
The same name_factors function sorts and signs the oblique solution, and the factor correlations are signed to match. Two things to read. The story does not change: every anchor still loads on its own factor, now even more cleanly (0.75 to 0.78, with every other loading near zero). And the factors correlate at 0.36 to 0.47. Those correlations are where the 0.11 to 0.20 cross loadings in the varimax table came from: varimax had to spread the shared good mood across every column. Room is the most independent opinion, which matches the way the data was generated. If two factors had correlated at 0.8, they would probably be one, and I would report three.
Example: turning the axes by 45 degrees
Why rotation never changes the fit takes one line of NumPy. A question loads 0.60 on two factors. Turn both axes by 45 degrees:
item = np.array([0.60, 0.60])
c = s = np.sqrt(0.5) # cos and sin of 45 degrees
turned = np.array([[c, s], [-s, c]]) @ item
print(turned.round(2), (item ** 2).sum().round(2), (turned ** 2).sum().round(2))
# [0.85 0. ] 0.72 0.72
The question now loads 0.85 on one factor and 0 on the other, and its communality, , has not moved. Rotation buys readability at no cost in fit.
Step nine: reliability and split half stability
Two checks decide whether the factors are measured well enough to use. Reliability asks whether the questions of one factor agree with each other. Cronbach's alpha is the usual measure:15
Here is the number of questions in the factor, the variance of question , and the variance of the sum of the questions per guest. If the questions agree, the sum varies much more than the parts, and alpha approaches one. A value of at least 0.70 is the level usually treated as acceptable.16 Variances are explained in Foundations: spread.
Stability asks whether the structure comes back on different guests. Split the sample at random, fit each half, and compare the loadings of each factor with Tucker's congruence coefficient:
where and are the loadings of question on the same factor in the two halves. It reads like a correlation that does not subtract the average, see Foundations: spread. Lorenzo Seva and ten Berge found that values from 0.85 to 0.94 indicate fair similarity and values above 0.95 mean the two factors can be considered equal.17
Example: alpha for the four factors
def cronbach_alpha(block):
k = block.shape[1]
return k / (k - 1) * (1 - block.var(ddof=1).sum() / block.sum(axis=1).var(ddof=1))
members = named.abs().idxmax(axis=1) # each question's home factor
for factor in anchors.values():
cols = members[members == factor].index
print(factor, len(cols), round(cronbach_alpha(items23[cols]), 2))
# service 6 0.87
# room 6 0.87
# food 5 0.83
# value 6 0.86
For Service, the six question variances add up to 9.31 and the variance of each guest's six question sum is 33.86, so . All four factors are well above 0.70.
Example: the two halves agree
def fit_named(frame, seed=0):
z = StandardScaler().fit_transform(frame)
f = FactorAnalysis(n_components=4, rotation="varimax", random_state=seed).fit(z)
return name_factors(pd.DataFrame(f.components_.T, index=frame.columns), anchors)[0]
def congruence(a, b):
return (a * b).sum() / np.sqrt((a ** 2).sum() * (b ** 2).sum())
half = np.random.default_rng(7).permutation(len(items23)) < len(items23) // 2
first, second = fit_named(items23[half]), fit_named(items23[~half])
print({f: round(float(congruence(first[f], second[f])), 3) for f in anchors.values()})
# {'service': 0.996, 'room': 0.993, 'food': 0.99, 'value': 0.992}
The anchors do the heavy lifting again: without them, the two halves would return the factors in different orders and signs, and the comparison would match Service in one half with Value in the other. Every congruence is 0.99 or more, so the structure is the same in both halves of 670 guests. That is the second of the three tests passed. With a few hundred answers instead of 1,340 it often is not, and Costello and Osborne's simulations show why: at five answers per question, the correct structure came back in only 40% of samples, at 20 per question in 70%.12 Chalkline has 58 answers per question.
Step ten: from four factors to one decision
The third test, money, turns the factor solution into a decision. Compute each guest's four factor scores, the estimated value of each hidden opinion, and regress the recommendation score on them with statsmodels, as in price elasticity with regression in Python.
Example: the regression on factor scores
scores = pd.DataFrame(fa.transform(Z23)[:, order] * signs,
columns=list(anchors.values()), index=survey.index)
print(scores.corr().round(2).abs().where(lambda m: m < 1).max().max())
model = sm.OLS(survey["recommend"], sm.add_constant(scores)).fit()
print(pd.DataFrame({"coef": model.params, "se": model.bse}).round(2).to_string())
print("R squared", round(model.rsquared, 3))
# 0.06
# coef se
# const 8.17 0.03
# service 0.56 0.03
# room 0.44 0.03
# food 0.54 0.04
# value 0.69 0.03
# R squared 0.476
fa.transform returns the scores in the fitted order and sign, so the same order and signs from the naming step put them in named columns. Because the varimax factors are uncorrelated, their scores nearly are too (no pair above 0.06), and the four coefficients do not fight each other the way 23 correlated questions would. Each can be read on its own:
Value is the largest lever, times the effect of Room. With a standard error of 0.03 on each, the gap of 0.25 between them is about six times its own standard error, so it is not noise. The model explains 47.6% of the variance in recommendation, the other half is everything a survey cannot see. The Value factor is built as much from "extras were fairly priced" as from the room rate, so the next question is which extras, and that is a pricing decision rather than a refurbishment. Room, where Anna planned to spend most of next year's budget, is the weakest of the four levers for the guests she already has.
Step eleven: Northgate Hampers, PCA on behaviour
The second example needs no survey and no theory of hidden opinions. Priya wants the fewest uncorrelated columns that keep most of the information in 18 behavioural variables, so that the segmentation in the next chapter of the Marketing Analytics series does not count spend three times. That is a PCA job.
The generated table follows the Marketing Analytics chapter: how much and how often customers buy, how they gift (message cards, other delivery addresses, December, a company on the invoice), how they respond to offers (vouchers, discount depth, email clicks, days from offer to order), and four columns that turn out to matter little (share of orders on a phone, newsletter, reviews, returns). Each customer carries three hidden habits, and every column is a transformed, noisy version of one of them.
Example: generating 6,200 customers
def expit(x):
return 1 / (1 + np.exp(-x))
rng = np.random.default_rng(22)
n = 6_200
volume, gifting, deals = rng.standard_normal((3, n)) # three hidden habits per customer
e = lambda: rng.standard_normal(n) # fresh noise for every column
orders = np.maximum(1, np.round(np.exp(1.0 + 0.68 * (0.93 * volume + 0.37 * e())))).astype("int64")
avg_order_value = np.exp(np.log(52) + 0.30 * (0.40 * gifting + 0.92 * e())).round(2)
customers = pd.DataFrame({
"orders": orders,
"spend": (orders * avg_order_value).round(2),
"avg_order_value": avg_order_value,
"categories": np.minimum(9, 1 + rng.binomial(orders, 0.45)),
"months_active": np.clip(np.round(1 + 13 * expit(1.6 * (0.80 * volume + 0.60 * e()))), 1, 14).astype("int64"),
"days_since_last": np.round(np.exp(4.6 - 0.75 * (0.62 * volume + 0.78 * e()))).astype("int64"),
"gift_message_share": expit(-0.3 + 1.7 * (0.78 * gifting + 0.63 * e())).round(3),
"other_address_share": expit(-0.5 + 1.7 * (0.78 * gifting + 0.63 * e())).round(3),
"december_share": expit(-0.9 + 1.5 * (0.74 * gifting + 0.67 * e())).round(3),
"company_invoice_share": expit(-2.5 + 1.5 * (0.55 * gifting + 0.84 * e())).round(3),
"voucher_share": expit(-0.8 + 1.6 * (0.80 * deals + 0.60 * e())).round(3),
"discount_depth": (5 + 15 * expit(1.5 * (0.80 * deals + 0.60 * e()))).round(1),
"offer_click_rate": expit(-2.2 + 1.0 * (0.76 * deals + 0.65 * e())).round(3),
"days_offer_to_order": np.round(np.exp(2.2 - 0.8 * (0.70 * deals + 0.71 * e()))).astype("int64"),
"phone_share": rng.beta(2, 2, n).round(3),
"newsletter": (rng.random(n) < 0.45).astype("int64"),
"reviews": rng.poisson(0.6, n),
"returns": rng.poisson(0.15, n),
}, index=pd.Index(np.arange(1, n + 1), name="customer_id"))
print(customers.shape, round(customers["orders"].mean(), 1), round(customers["orders"].std(), 1))
# (6200, 18) 3.4 2.6
The average customer has 3.4 orders with a standard deviation of 2.6, as in the Marketing Analytics chapter. In a real project this table is built from the cleaned order export: refund rows, test orders and staff orders removed, order times converted from UTC to the shop's own time zone before anything is counted as "December". A December share computed on UTC timestamps moves every order placed after midnight on New Year's Eve, and a gifting component built on it inherits the error.
Example: log the long tails first
skewed = ["orders", "spend", "avg_order_value", "days_since_last", "days_offer_to_order"]
print(customers[skewed].skew().round(1).to_dict())
print(round(customers["orders"].corr(customers["spend"]), 2),
round(np.log1p(customers["orders"]).corr(np.log1p(customers["spend"])), 2))
# {'orders': 2.5, 'spend': 3.3, 'avg_order_value': 0.9, 'days_since_last': 3.0, 'days_offer_to_order': 3.7}
# 0.89 0.91
A skewness of 3.3 means a long right tail: a few corporate buyers who spend many times the median. Left as they are, they pull the first component towards "the whales against everybody else". np.log1p, the logarithm of one plus the value, compresses the tail and copes with zeros. After it, orders and spend correlate at 0.91, the number used by hand in step six.
The two column case from step six, checked on this table:
r = np.log1p(customers["orders"]).corr(np.log1p(customers["spend"]))
two = np.array([[1, r], [r, 1]])
values, vectors = np.linalg.eigh(two) # numpy returns smallest first
print(round(r, 2), values[::-1].round(2), np.abs(vectors[:, -1]).round(4))
print("share:", round(values[-1] / 2, 3), " loading:", round(np.sqrt(0.5) * np.sqrt(values[-1]), 2))
# 0.91 [1.91 0.09] [0.7071 0.7071]
# share: 0.956 loading: 0.98
The same 1.91, 95.5% and 0.98 as worked by hand.
Example: eigenvalues and parallel analysis
X = customers.copy()
X[skewed] = np.log1p(X[skewed]) # tame the long tails first
Z = StandardScaler().set_output(transform="pandas").fit_transform(X)
eig = np.linalg.eigvalsh(np.corrcoef(Z, rowvar=False))[::-1]
noise = parallel_analysis(*Z.shape)
print(pd.DataFrame({"northgate": eig[:10], "random": noise[:10]}).round(2).T.to_string())
print("Kaiser keeps:", int((eig > 1).sum()), " parallel analysis keeps:", int((eig > noise).argmin()))
print("kept share:", round(eig[:3].sum() / len(eig), 3))
# 0 1 2 3 4 5 6 7 8 9
# northgate 3.52 2.66 2.60 1.05 1.00 0.99 0.97 0.89 0.71 0.64
# random 1.11 1.09 1.07 1.06 1.05 1.04 1.03 1.02 1.01 1.00
# Kaiser keeps: 5 parallel analysis keeps: 3
# kept share: 0.487
Here the rules disagree, and the disagreement teaches more than agreement would. The fourth eigenvalue, 1.05, passes Kaiser's rule and fails parallel analysis, which gives 1.06 in fourth place. The fifth sits at 1.003, which rounds to 1.00 and still passes Kaiser. Components four to seven, all close to one, are the four unrelated columns (phone, newsletter, reviews, returns) shuffled among themselves: each variable that correlates with nothing contributes an eigenvalue of about one. Kaiser would keep two of them as "components". Parallel analysis keeps three, which carry of the variance (the code prints 0.487, because it uses the unrounded eigenvalues).
Example: three components, rotated and named
from factor_analyzer.rotator import Rotator
pca = PCA(n_components=3).fit(Z)
loadings = pd.DataFrame(pca.components_.T * np.sqrt(pca.explained_variance_), index=Z.columns)
rotated = pd.DataFrame(Rotator(method="varimax").fit_transform(loadings.to_numpy()), index=Z.columns)
print("share after rotation:", ((rotated ** 2).sum() / len(rotated)).round(3).to_list(),
" total:", round(float((rotated ** 2).sum().sum() / len(rotated)), 3))
# share after rotation: [0.193, 0.147, 0.148] total: 0.488
anchors = {"orders": "volume", "gift_message_share": "gifting", "voucher_share": "deal"}
order = [rotated.loc[a].abs().idxmax() for a in anchors]
signs = np.array([np.sign(rotated.loc[a, k]) for a, k in zip(anchors, order)])
components = rotated[order] * signs
components.columns = list(anchors.values())
for c in components:
big = components[c].abs().sort_values(ascending=False).index[:5]
print(c, components.loc[big, c].round(2).to_dict())
# volume {'orders': 0.95, 'spend': 0.91, 'months_active': 0.8, 'categories': 0.79, 'days_since_last': -0.68}
# gifting {'gift_message_share': 0.81, 'other_address_share': 0.81, 'december_share': 0.79, 'company_invoice_share': 0.61, 'avg_order_value': 0.55}
# deal {'voucher_share': 0.84, 'discount_depth': 0.83, 'offer_click_rate': 0.79, 'days_offer_to_order': -0.78, 'december_share': 0.04}
Rotating principal components is common practice when the goal is readable inputs, and the reasoning is the same as for factors: the rotation moves variance between the kept components but not out of them, , the same total as before give or take rounding. Rotated, they are no longer "principal" in the strict sense, because the first no longer carries the most variance it could.
| Component | Share after rotation | Variables with the largest loadings |
|---|---|---|
| Volume | 19.3% | orders 0.95, spend 0.91, months active 0.80, categories 0.79, days since last order minus 0.68 |
| Gifting | 14.8% | gift message share 0.81, other address share 0.81, December share 0.79, company on invoice 0.61, average order value 0.55 |
| Deal | 14.7% | voucher share 0.84, discount depth 0.83, offer click rate 0.79, days from offer to order minus 0.78 |
The negative loadings are the meaningful kind. A customer who buys a lot was, almost by definition, here recently, so "days since last order" moves against Volume. A deal sensitive customer orders the day the voucher lands, so "days from offer to order" moves against Deal. The anchor step only fixes the sign of the component as a whole, so that a high Volume score means many orders.
Example: scores you can hand to the next analysis
weights = np.linalg.pinv(components.to_numpy().T) # from loadings back to scores
ng_scores = pd.DataFrame(Z.to_numpy() @ weights, index=Z.index, columns=components.columns)
print(ng_scores.corr().round(2).to_string())
# volume gifting deal
# volume 1.0 -0.0 0.0
# gifting -0.0 1.0 -0.0
# deal 0.0 -0.0 1.0
The pseudo inverse of the transposed loadings turns the standardised table into scores, one per customer and component. Because the rotation was orthogonal, the three scores correlate at exactly zero, each with a standard deviation of one. A clustering algorithm such as k means now treats each dimension fairly instead of counting spend three times. The Python segmentation chapter in this series builds on these three columns.
Step twelve: freeze the recipe
A component score means "how far above this year's average Northgate customer, measured with this year's weights". If you refit the scaler and the PCA every month on whoever is in the table, the average moves, the weights move, and a customer whose behaviour never changed gets a new score. Worse, a refit can return the components in a different order or sign, as step seven showed. The fix is to fit the recipe once, save it, and only apply it afterwards. scikit learn's pipelines and joblib, which scikit learn uses for saving fitted objects,18 make that a few lines. How to keep such files under version control and test them is covered in a reproducible Python analysis workflow.
Example: next month's customers through this year's recipe
import joblib
from sklearn.pipeline import make_pipeline
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import FunctionTransformer
# The recipe: log the skewed columns, standardise with THIS year's means and spreads
prep = make_pipeline(
make_column_transformer((FunctionTransformer(np.log1p, feature_names_out="one-to-one"), skewed),
remainder="passthrough", verbose_feature_names_out=False),
StandardScaler(),
).set_output(transform="pandas")
prep.fit(customers)
joblib.dump({"prep": prep, "weights": weights, "names": list(components.columns)},
"northgate_components.joblib")
# Next month: new rows go through the frozen recipe, nothing is refitted
saved = joblib.load("northgate_components.joblib")
new = customers.sample(3, random_state=1) # stand in for next month's customers
z_new = saved["prep"].transform(new)[customers.columns]
print(pd.DataFrame(z_new.to_numpy() @ saved["weights"], index=new.index,
columns=saved["names"]).round(2).to_string())
# volume gifting deal
# customer_id
# 3280 -0.44 -0.62 -0.86
# 1692 -0.04 0.34 -0.70
# 5606 0.25 1.32 -1.00
The three customers get exactly the scores they had in ng_scores, which is the check that the saved recipe reproduces the analysis. The column transformer puts the logged columns first, so [customers.columns] restores the original order before the weights are applied: skip it and every score is silently wrong. Customer 5606 scores 1.32 on Gifting, more than one standard deviation above the average customer of the year the recipe was fitted, and that sentence stays true next month. Write the fitting date into the file name or a field, and refit deliberately, once a year or after a big change in the range, never by accident.
My view
My view: for a survey that was written to measure a few things, fit a factor analysis with varimax, check it with oblimin, and report the oblique factor correlations next to the loadings. For behaviour, fit PCA on logged and standardised columns, rotate for readability, and do not pretend the components are opinions. Count with parallel analysis every time. Kaiser's rule is a default, not a method, and the Northgate example shows it keeping noise.
The more important part of my view is about the three tests. Libraries make it easy to produce a loadings table, and a loadings table always looks like a result. The ten lines of parallel analysis, the split halves and the regression on an outcome are what separate a finding from a pattern you hoped to see, and none of them is printed by default. I would rather present three factors that pass all three than five that look tidy.
And I write the small pieces myself, KMO, parallel analysis, alpha, congruence, naming by anchors, each under fifteen lines. The factor_analyzer episode is the reason: a well known package stopped working with a routine scikit learn upgrade, and the analyses that depended on it stopped with it. scikit learn and NumPy are maintained by large communities. Code you wrote and understand is maintained by you. That combination ages better than a dependency nobody on the team can read.
Mistakes worth avoiding
Reading components_ from PCA as loadings. They are weights. Multiply by the square root of explained_variance_ first.
Naming factors by position. The order and sign of factors are arbitrary and can change with every refit. Name them from anchor columns, and let the code stop if two anchors share a factor.
Factoring the raw export. Codes for "not applicable", straightliners and duplicated responses change the correlations before any model sees them. In the example, 0 for "did not eat dinner" cut a key correlation from 0.57 to 0.21.
Filling gaps with the average. It invents agreement. Use complete answers, or leave the question out and report it separately.
Trusting Kaiser's rule alone. It kept five components at Northgate where three are real.
Refitting the recipe every month. Scores stop being comparable, and component signs can flip. Fit once, save, apply.
Pinning nothing. A factor analysis that ran in March may not run in June. Write the package versions into the project, as the first code block of this chapter does.
Stopping at the loadings table. Without a split half check and a link to an outcome, the factors are a description, not a decision.
Conclusion
Twenty four correlated questions at Chalkline turned out to be four opinions, measured six times each, and one WiFi question that measures the router. In Python that takes a cleaning function, a standardisation, an eigenvalue check against random data, a factor analysis with varimax from scikit learn, an oblique check with factor_analyzer's Rotator, and a regression of the outcome on the scores. Four factors beat noise, survived both halves and explained 48% of recommendation, and Value turned out to be the biggest lever, Room the smallest. At Northgate, PCA turned 18 columns into Volume, Gifting and Deal, three uncorrelated scores frozen in a recipe that next month's customers can run through unchanged.
The concepts are all in principal components and factor analysis for marketers. Data science, analytics dashboards and data storytelling are a core part of my work for clients, and the Data Science page describes how I approach it. If you have a survey or a customer table with too many columns, the free workshop is the place to start, and my prices are published on the pricing page. You keep the code, the accounts and the data.
