Written and maintained by CASRAI Editorial Board
Published
On this page
Factor analysis in Python is a multivariate statistical technique used to uncover unobserved latent constructs that explain the shared variance and correlation structure among observed numeric variables. Using specialized open-source libraries such as factor_analyzer and scikit-learn, researchers evaluate dataset suitability through Bartlett’s test of sphericity and Kaiser-Meyer-Olkin (KMO) sampling adequacy, extract latent dimensions via minimum residual or maximum likelihood estimation, apply orthogonal or oblique rotations to clarify factor loadings, and compute reproducible factor scores for downstream empirical analysis.
What factor analysis in Python is used for in research
In quantitative academic and scientific research, investigators frequently administer multi-item questionnaires, psychometric batteries, or high-dimensional behavioral instruments where dozens of individual questions measure a smaller number of underlying psychological or operational traits. For example, a forty-item survey evaluating organizational climate may reflect three fundamental latent dimensions: managerial transparency, peer collaboration, and structural autonomy. Factor analysis provides the formal mathematical framework to model these latent constructs as unobserved random variables that linearly drive the responses observed across measured survey items.
The core objective of factor analysis is data reduction and latent structure discovery while explicitly partitioning common variance from unique error variance. Unlike purely empirical dimensionality reduction, exploratory factor analysis assumes a reflective measurement model where observed indicators covary because they share common latent causes. Researchers following rigorous exploratory factor analysis principles use Python to test whether survey items load cleanly onto theorized constructs without arbitrary cross-loadings before specifying structural equation models. When pre-existing theory specifies exact item-to-factor relationships, researchers transition to confirmatory factor analysis workflows to formally test goodness-of-fit indices. Investigators evaluating structural assumptions can examine the detailed confirmatory versus exploratory factor analysis comparison to select the appropriate estimation paradigm.
A critical methodological distinction in computational data science is the difference between Principal Component Analysis (PCA) and Common Factor Analysis. PCA transforms p correlated variables into p uncorrelated linear combinations that explain total observed variance, including specific and random measurement error. In contrast, common factor analysis decomposes the observed correlation matrix into two distinct components: common variance (communalities accounted for by k latent factors, where k is less than p) and unique variance (comprising variable-specific variance and measurement error). When the research aim is construct validation or latent trait discovery rather than generic predictive feature reduction, factor analysis is the methodologically required approach.
Python has emerged as an industry-standard environment for multivariate analysis due to its extensive scientific computing ecosystem, programmatic reproducibility, and seamless integration with automated data cleaning pipelines. Scripting factor extraction and diagnostic validation in Python eliminates the manual copy-paste errors and proprietary licensing constraints inherent to traditional spreadsheet workflows.
How to install or access factor analysis packages in Python
Factor analysis in Python is implemented across three primary open-source packages, each tailored to distinct analytical workflows. The most feature-complete library for psychometric scale validation and exploratory factor analysis is factor_analyzer, which ports the core algorithms of R’s psych package into native Python. The second tool is scikit-learn, which provides a generative latent variable implementation designed for machine learning preprocessing pipelines. The third tool is statsmodels, which supplies classical multivariate estimation tables.
To establish a clean, reproducible research environment, install the required packages within an isolated virtual environment using the Python Package Index (PyPI):
python -m venv stats-env
source stats-env/bin/activate
pip install factor-analyzer scikit-learn statsmodels pandas numpy matplotlib
The roles and capabilities of these Python libraries differ substantially:
- factor_analyzer (v0.5.1): Built specifically for survey research and psychometrics. It includes pre-extraction diagnostic tests (Bartlett’s sphericity, Kaiser-Meyer-Olkin test), multiple extraction algorithms (minimum residual, maximum likelihood, principal axis factoring), diverse orthogonal and oblique rotation methods (Varimax, Promax, Oblimin, Quartimax), and automated calculation of communalities and factor variances.
- scikit-learn (sklearn.decomposition.FactorAnalysis): Implements a linear generative latent model estimated via the Expectation-Maximization (EM) algorithm. It assumes Gaussian latent variables and feature-specific noise. It is optimized for dimensional reduction within scikit-learn pipelines, though it lacks built-in psychometric adequacy tests and oblique rotation options.
- statsmodels (statsmodels.multivariate.factor.Factor): Provides classical econometric factor extraction supporting principal factor and maximum likelihood methods, outputting detailed parameter summaries and eigenvalue decompositions.
How to perform factor analysis in Python step by step
Executing an exploratory factor analysis in Python requires a systematic, six-step protocol that validates statistical assumptions before fitting the final rotated model.
- Data screening and missing value handling: Verify that observed variables are continuous or multi-point Likert scales (typically 5-point or 7-point scales with approximately symmetric distributions). Inspect the dataset for missing values, dropping incomplete cases or imputing them using principled multivariate techniques. Variables must be numeric and appropriately scaled.
- Testing dataset factorability and sampling adequacy: Before extracting latent factors, confirm that observed variables share sufficient intercorrelations to justify factor analysis. Compute Bartlett’s test of sphericity and the Kaiser-Meyer-Olkin (KMO) measure of sampling adequacy using
factor_analyzer.factor_analyzerfunctions. Bartlett’s test checks the null hypothesis that the correlation matrix is an identity matrix (requiring a p-value below 0.05). The overall KMO score measures the proportion of common variance among variables, requiring a threshold of at least 0.60 to proceed. - Determining the number of factors to retain: Fit an initial unrotated factor model across all available variables to extract eigenvalues. Two classical decision heuristics guide factor retention: the Kaiser Criterion (retaining factors with eigenvalues greater than 1.0) and Cattell’s Scree Plot (identifying the visual elbow where the slope flattens into residual scree).
- Model fitting and extraction: Initialize the
FactorAnalyzerclass with the chosen factor count and extraction method. Common extraction choices includemethod='minres'(minimum residual / ordinary least squares, robust against non-normality) andmethod='ml'(maximum likelihood, which allows formal likelihood-ratio testing but requires multivariate normality). - Applying factor rotation: Unrotated factor matrices are mathematically arbitrary and difficult to interpret because the first factor typically loads heavily on all variables. Apply rotation to achieve simple structure. Select an orthogonal rotation (such as
rotation='varimax') if factors are assumed to be independent, or an oblique rotation (such asrotation='promax'or'oblimin') if underlying constructs are theoretically correlated. - Extracting loadings, communalities, and factor scores: Inspect the rotated factor loading matrix, variable communalities, and total variance explained. If observation-level scores are needed for secondary regression or clustering, use the
transform()method while reviewing validated methods for computing factor scores to ensure scoring indeterminacy is addressed.
The following Python script demonstrates this complete six-step workflow:
import numpy as np
import pandas as pd
from factor_analyzer import FactorAnalyzer
from factor_analyzer.factor_analyzer import calculate_bartlett_sphericity, calculate_kmo
np.random.seed(42)
n_samples = 150
latent_1 = np.random.normal(0, 1, n_samples)
latent_2 = np.random.normal(0, 1, n_samples)
data = pd.DataFrame({
'Tech_1': latent_1 * 0.85 + np.random.normal(0, 0.35, n_samples),
'Tech_2': latent_1 * 0.78 + np.random.normal(0, 0.40, n_samples),
'Tech_3': latent_1 * 0.82 + np.random.normal(0, 0.38, n_samples),
'Comm_1': latent_2 * 0.80 + np.random.normal(0, 0.36, n_samples),
'Comm_2': latent_2 * 0.75 + np.random.normal(0, 0.42, n_samples),
'Comm_3': latent_2 * 0.84 + np.random.normal(0, 0.32, n_samples),
})
chi_sq, p_val = calculate_bartlett_sphericity(data)
kmo_per_item, kmo_total = calculate_kmo(data)
print(f"Bartlett p-value: {p_val:.4e}, KMO Total: {kmo_total:.3f}")
unrotated = FactorAnalyzer(n_factors=data.shape[1], rotation=None)
unrotated.fit(data)
ev, _ = unrotated.get_eigenvalues()
print("Eigenvalues:", np.round(ev, 3))
fa = FactorAnalyzer(n_factors=2, rotation='varimax', method='minres')
fa.fit(data)
loadings = pd.DataFrame(fa.loadings_, index=data.columns, columns=['Factor_1', 'Factor_2'])
communalities = pd.Series(fa.get_communalities(), index=data.columns, name='h2')
variance = pd.DataFrame(fa.get_factor_variance(), index=['SS_Loadings', 'Proportion_Var', 'Cumulative_Var'])
print(loadings.round(3))
print(communalities.round(3))
print(variance.round(3))
scores = fa.transform(data)
print(f"Computed factor score shape: {scores.shape}")
How to read the output
Interpreting factor analysis output requires examining three interconnected analytical tables: the rotated factor loading matrix, the communalities vector, and the factor variance breakdown.
1. Rotated Factor Loading Matrix: Factor loadings represent the standardized regression coefficients between observed items and latent factors. Loadings range from -1.0 to +1.0. Psychometric conventions establish the following interpretive thresholds:
- Loadings ≥ 0.70: Excellent indicator; the latent factor explains at least 49% of the observed item’s variance.
- Loadings 0.50 to 0.69: Strong, practically significant indicator.
- Loadings 0.30 to 0.49: Minimally acceptable loading; retained if supported by theoretical consensus.
- Loadings below 0.30: Uninformative item that fails to associate meaningfully with the construct.
- Cross-Loadings: Items that load at 0.32 or higher across multiple factors exhibit cross-loading, creating construct ambiguity and indicating items for potential revision.
2. Communalities (h²): Communality denotes the proportion of variance in an observed variable explained by the retained common factors. In an orthogonal solution, it equals the sum of squared loadings across factors for that item: hᵢ² = ∑ λᵢⱼ². The remaining proportion, uᵢ² = 1 – hᵢ², represents unique variance (item-specific variance plus measurement error). Items with communalities below 0.30 contribute little common information to the factor model and degrade scale reliability.
3. Factor Variance Summary: The get_factor_variance() method returns three metrics per factor:
- SS Loadings: The sum of squared loadings for each factor, reflecting the total variance accounted for by that rotated factor.
- Proportion Variance: The percentage of total dataset variance explained by the individual factor.
- Cumulative Variance: The running sum of variance explained. In behavioral research, models accounting for 50% to 60% of cumulative variance are widely considered satisfactory.
Troubleshooting factor analysis in Python
During model specification and estimation, empirical datasets frequently trigger mathematical anomalies or convergence errors. Researchers must recognize and resolve four primary computational problems:
- Singular Matrix and Multicollinearity (LinAlgError): When observed variables exhibit near-perfect correlation (r exceeding 0.90) or variables exceed sample size (p exceeds n), the correlation matrix becomes non-positive definite. Resolve this by inspecting correlation heatmaps, removing redundant items, and ensuring at least 5 to 10 observations per variable.
- Heywood Cases and Ultra-Heywood Cases: A Heywood case occurs when an item’s estimated communality reaches or exceeds 1.0 (hᵢ² ≥ 1.0), implying zero or negative unique variance. Common causes include over-extracting factors, cross-loadings, small samples, or poor items. To resolve a Heywood case, reduce factor count, drop problematic items, or switch to the minimum residual algorithm (
method='minres') with bounded communality constraints. - Low Kaiser-Meyer-Olkin Scores (below 0.60): When overall KMO drops below 0.60, the correlation matrix contains too much partial variance relative to common variance. Inspect the individual variable KMO scores returned by
calculate_kmo(data)[0]. Variables with individual KMO values below 0.50 should be iteratively removed, re-evaluating overall KMO after each exclusion until sampling adequacy is achieved. - Non-Convergence in Maximum Likelihood Estimation: The maximum likelihood algorithm relies on iterative optimization to maximize the log-likelihood function. If the optimization reaches the maximum iteration limit without satisfying tolerance thresholds, the model fails to converge. Researchers should increase
max_iter, verify multivariate normality, or adopt principal axis factoring (method='principal') or minimum residual extraction, which do not rely on Gaussian likelihood maximization.
Free alternatives to Python factor analysis libraries
While Python provides a flexible, code-based environment for factor analysis, several free, open-source, and proprietary software alternatives exist across the scientific computing landscape. The choice of tool depends on whether researchers prioritize statistical depth, scriptable automation, or graphical user interface accessibility.
| Software / Package | Environment Type | Primary Strength | Key Limitation | Licensing Model |
|---|---|---|---|---|
| factor_analyzer (Python) | Scripting / Python Library | Native integration with Python data science pipelines, built-in adequacy tests | Limited diagnostic plotting compared to specialized R packages | Open Source (BSD-3-Clause) |
| R (psych and lavaan packages) | Scripting / R Environment | Comprehensive gold standard for psychometrics, advanced EFA, bifactor models, and CFA | Requires R language proficiency and separate pipeline integration | Open Source (GPL) |
| scikit-learn (Python) | Scripting / Machine Learning | Seamless compatibility with ML pipelines, cross-validation, and feature unions | No built-in KMO, Bartlett tests, or oblique rotations | Open Source (BSD-3-Clause) |
| JASP / jamovi | Point-and-Click GUI | Dynamic R-powered statistical outputs, intuitive interface, APA-formatted tables | Less suited for batch automation or high-throughput ETL pipelines | Open Source (GPL / AGPL) |
| Microsoft Excel | Spreadsheet | Ubiquitous availability, familiar tabular data entry | No native factor analysis in Data Analysis ToolPak; requires third-party add-ins | Commercial / Proprietary |
The companion dataset presented below provides a structured technical comparison of Python factor analysis implementations, extraction solvers, and rotation capabilities compiled from official documentation.
Factor analysis in Excel and standalone statistical tools
A widespread question among researchers transitioning from spreadsheet analysis is whether factor analysis can be performed directly within Microsoft Excel. The built-in Excel Data Analysis ToolPak provides basic analytical procedures, including Descriptive Statistics, Correlation, Covariance, Regression, and ANOVA. However, Microsoft Excel does not include native exploratory or confirmatory factor analysis functions, nor does it provide an automated routine for Principal Component Analysis.
To execute factor analysis in Excel, researchers are historically forced to adopt one of three workarounds:
- Manual Matrix Algebra: Computing the correlation matrix using
=CORREL(), followed by custom matrix inversion, eigenvalue calculation, and Jacobi rotations using complex array formulas. This approach is highly vulnerable to cell-referencing errors and cannot scale past a few variables. - Commercial Add-ins: Installing third-party commercial software packages such as XLSTAT, which embed statistical modeling menus directly into Excel at substantial annual subscription costs.
- Macro Libraries: Installing free VBA macro packs, such as the Real Statistics Resource Pack, which add supplemental statistical routines but present security warnings and compatibility barriers across enterprise IT environments.
In contrast, executing factor analysis in Python provides automated algorithmic extraction, reproducible script files that can be shared in open-science repositories, version-controlled workflows, and complete freedom from commercial add-in dependencies.
Frequently asked questions
What is the difference between PCA and Factor Analysis in Python?
Principal Component Analysis (PCA) is an empirical dimensionality reduction technique that maximizes total observed variance, transforming p original variables into p orthogonal components without distinguishing between common variance and error variance. Factor analysis is a latent variable modeling technique that partitions variance into common variance (shared across items) and unique variance (specific error). In Python, use scikit-learn PCA when your objective is general feature compression for predictive models; use factor_analyzer when validating measurement instruments, evaluating survey scales, or identifying unobserved psychological or operational constructs.
How do you choose the number of factors to retain in Python?
Researchers determine the optimal factor count by combining mathematical criteria with domain theory. The most common empirical heuristic is the Kaiser criterion, which retains all factors with eigenvalues greater than 1.0 from the initial unrotated correlation matrix. A second approach is Cattell’s scree plot, where eigenvalues are plotted in descending order and factors preceding the visual elbow inflection point are retained. A third, highly robust method is Horn’s Parallel Analysis, which compares sample eigenvalues against eigenvalues generated from random synthetic datasets with identical dimensions. In Python, call fa.get_eigenvalues() in factor_analyzer to evaluate Kaiser and scree thresholds.
What is the difference between factor_analyzer and scikit-learn?
The factor_analyzer package is designed specifically for statistical psychometrics and survey research, providing pre-extraction sampling adequacy diagnostics (Bartlett’s test and KMO), multiple estimation solvers (MinRes, ML, Principal Axis), and oblique rotations (Promax, Oblimin). In contrast, scikit-learn.decomposition.FactorAnalysis implements a linear generative model with Gaussian latent variables estimated via Expectation-Maximization. The scikit-learn class is built for machine learning pipelines and unsupervised feature extraction, but it does not output psychometric test statistics, scree eigenvalues, or oblique rotation matrices.
What is factor rotation and when should you choose varimax versus promax?
Factor rotation is a post-extraction mathematical transformation that rotates the factor axes to achieve simple structure, ensuring that each observed variable loads strongly on one factor and near zero on all others. Varimax is an orthogonal rotation that forces factors to remain completely uncorrelated (at 90-degree angles in factor space), which is appropriate when theoretical constructs are assumed independent. Promax is an oblique rotation that allows factors to correlate, which is standard in social and behavioral sciences where human traits, attitudes, and operational performance metrics are naturally interrelated.
What is an acceptable Kaiser-Meyer-Olkin (KMO) score for factor analysis?
The Kaiser-Meyer-Olkin (KMO) measure of sampling adequacy assesses the degree of common variance among variables relative to partial correlations. Scores range from 0.0 to 1.0. Psychometric conventions (Kaiser and Rice, 1974) establish that a total KMO score of 0.60 is the minimum acceptable threshold for factor analysis. Scores between 0.70 and 0.79 are considered middling, 0.80 to 0.89 are meritorious, and 0.90 or above are marvelous. If overall KMO falls below 0.60, variables do not share enough common variance to produce reliable latent constructs.
How does factor analysis in Excel compare to Python?
Microsoft Excel does not possess native exploratory or confirmatory factor analysis routines within its Data Analysis ToolPak, restricting built-in multivariate operations to simple correlation and covariance tables. Conducting factor analysis in Excel requires third-party proprietary add-ins (such as XLSTAT) or VBA macro libraries. In contrast, Python offers comprehensive, open-source, scriptable factor analysis libraries (such as factor_analyzer and statsmodels) that execute automated adequacy checks, iterative rotations, and factor score generation with complete scientific reproducibility.
Sources
- FactorAnalyzer Documentation: Welcome to the FactorAnalyzer documentation! (factor_analyzer 0.5.1 documentation), checked 2026-11-24
- FactorAnalyzer Documentation: API documentation (factor_analyzer 0.5.1 documentation), checked 2026-11-24
- scikit-learn: FactorAnalysis — scikit-learn 1.9.1 documentation, checked 2026-11-24
- scikit-learn: 2.5. Decomposing signals in components (matrix factorization problems) — scikit-learn 1.9.1 documentation, checked 2026-11-24
- statsmodels: statsmodels.multivariate.factor.Factor — statsmodels 0.15.0, checked 2026-11-24
Data: Python Factor Analysis Packages and Extraction Methods
Comparison of Python statistical libraries, extraction methods, rotation algorithms, and diagnostic tests for exploratory and confirmatory factor analysis compiled from official documentation.
Period covered: 2026. Coverage: Global.
| Package or Implementation | Primary Analytical Purpose | Adequacy Diagnostics | Supported Rotations | Estimation Solvers |
|---|---|---|---|---|
| factor_analyzer (v0.5.1) | Exploratory and confirmatory factor analysis; survey scale validation | Built-in Bartlett sphericity and KMO sampling adequacy functions | Varimax, Promax, Oblimin, Oblimax, Quartimax, Quartimin | Minimum Residual (minres), Maximum Likelihood (ml), Principal Axis Factoring |
| scikit-learn FactorAnalysis | Unsupervised dimensionality reduction and ML generative modeling | None (relies on external data preprocessing) | Varimax, Quartimax (orthogonal only) | Expectation-Maximization (EM) algorithm, SVD |
| statsmodels Factor | Classical multivariate modeling and covariance decomposition | Summary diagnostics for eigenvalues and communalities | Varimax, Quartimax, Promax (via statsmodels rotation module) | Principal Factor, Iterated Principal Factor, Maximum Likelihood |
Sources
- Welcome to the FactorAnalyzer documentation! — factor_analyzer 0.5.1 documentation (accessed 2026-11-24)
- FactorAnalysis — scikit-learn 1.9.1 documentation (accessed 2026-11-24)
- statsmodels.multivariate.factor.Factor — statsmodels 0.15.0 (accessed 2026-11-24)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







