Skip to content

Instantly share code, notes, and snippets.

@siyangni
Forked from lauracodecreations/Cronbach’s_alpha.md
Last active May 10, 2021 18:45
Show Gist options
  • Save siyangni/443a5722ed0d424c9ddccea96f82f53f to your computer and use it in GitHub Desktop.
Save siyangni/443a5722ed0d424c9ddccea96f82f53f 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.

# Write a function to perform Cronbach's Alpha Calculation
# Forked from Github: https://gist.github.com/lauramar6261/7b6b3ede3cb5f7e23c75f0a93ffb869e
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))
output= print('The score of the', nitems, 'itmes is', Calpha)
return output
@siyangni
Copy link
Author

Adjust the return fromat a little bit, now the output looks like: "The score of the n items is Calpha."

@iburunat
Copy link

What format should X be?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment