Confirmatory Factor Analysis in Python

7.3k Views Asked by At

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 .

2

There are 2 best solutions below

0
Zhiying Cui On

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))
6
Azadeh Feizpour On

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.