Skip to content

Instantly share code, notes, and snippets.

@lauracodecreations
Last active October 29, 2021 10:25
Show Gist options
  • Save lauracodecreations/7b6b3ede3cb5f7e23c75f0a93ffb869e to your computer and use it in GitHub Desktop.
Save lauracodecreations/7b6b3ede3cb5f7e23c75f0a93ffb869e to your computer and use it in GitHub Desktop.

Calculating Cronbach's Alpha using Python

Cronbach’s alpha is a measure of internal consistency, that is, how closely related a set of items are as a group. More information about this: https://stats.idre.ucla.edu/spss/faq/what-does-cronbachs-alpha-mean/

The code assumes that you already have uploaded your data in Azure ML, and that you have imported into Python. More information: https://gist.github.com/lauramar17/0fd5ea81be217a7ccd39cacaba7397b9.js

Method: It takes an unlimited number of parameters for the questions that you want to calculate its internal consistency.

To run:

CronbachAlpha2([<datasetname>['<columnname>']])

Example

CronbachAlpha2([frame['Q27'],frame['Q28'],frame['Q29']])

Note: "frame' is the name of the dataset, and the 'Q27' is the name of column.

import numpy as np
def svar(X):
n = float(len(X))
svar=(sum([(x-np.mean(X))**2 for x in X]) / n)* n/(n-1.)
return svar
def CronbachAlpha2(itemscores):
itemvars = [svar(item) for item in itemscores]
tscores = [0] * len(itemscores[0])
for item in itemscores:
for i in range(len(item)):
tscores[i]+= item[i]
nitems = len(itemscores)
#print "total scores=", tscores, 'number of items=', nitems
Calpha=nitems/(nitems-1.) * (1-sum(itemvars)/ svar(tscores))
return Calpha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment