Is there a package to perform Confirmatory Factor Analysis in python? I have found a few that can perform Exploratory Factor Analysis in python (scikitlearn, factor_analyzer etc), but I am yet to find a package that does CFA .
Asked
Active
Viewed 6,454 times
2 Answers
3
python 3.7.3 in Spyder (Anaconda Navigator)
factor_analyzer does CFA as well:
import necessary libraries
import pandas as pd
from factor_analyzer import FactorAnalyzer
importing sample data
df= pd.read_csv("test.csv")
Confirmatory factor analysis
from factor_analyzer import (ConfirmatoryFactorAnalyzer, ModelSpecificationParser)
model_dict = {"F1": ["V1", "V2", "V3", "V4"], "F2": ["V5", "V6", "V7", "V8"]}
model_spec = ModelSpecificationParser.parse_model_specification_from_dict(df, model_dict)
cfa = ConfirmatoryFactorAnalyzer(model_spec, disp=False)
cfa.fit(df.values)
cfa.loadings_
- V1 to V8 refer to the name of columns in your data frame that you'd like to allocate to each factor (F1 and F2). You need to replace V1 to V8 with appropriate column names based on your data set and hypothesis you're testing.

Azadeh Feizpour
- 49
- 1
- 6
-
This doesn't appear to work in python 3.7. I have tried to update factor_analyser to allow this but there seem's to be some incompatibility issues. – KevOMalley743 Oct 30 '19 at 22:01
-
I've used python 3.7.3 in Spyder. – Azadeh Feizpour Oct 31 '19 at 23:56
-
I created a new Virtual env and that has solved my issue. Thanks for the answer. – KevOMalley743 Nov 01 '19 at 00:02
-
"factor_analyzer does CFA as well" -- does it? Isn't the purpose of CFA to test hypotheses? This is just fitting a model. – Denziloe Mar 04 '21 at 22:11
-
CFA stands for Confirmatory Factor Analysis. This line imports CFA function from factor_analyzer _from factor_analyzer import (ConfirmatoryFactorAnalyzer, ModelSpecificationParser)_ After fitting the model, by looking at fit indexes and factor loadings (depending on what you're testing) you investigate your hypothesis. – Azadeh Feizpour Mar 11 '21 at 03:08
0
You can try the package psy (https://pypi.org/project/psy/). I cannot find its documentation, but I could read the comments which are written in Chinese.
Example:
import psy
# items is a pandas data frame containing item data
# Specify how the items are mapped to the factors
# In this case, all mapped to one factor
item_factor_mapping = np.array([[1]] * items.shape[1])
print(psy.cfa(items, item_factor_mapping))

Zhiying Cui
- 21
- 3