问题描述
我正在使用scipy.stats.spearmanr计算2个序数变量的Spearman等级相关性。我不确定是否要对它们进行编码。我尝试了两种方式,无论如何,该功能似乎都能吐出结果。所以我不确定该走哪条路。
from scipy import stats
# dummy data comparing one ordinal variable with another
print(stats.spearmanr(['always','never','sometimes','always'],['high','medium','low','low']))
>> SpearmanrResult(correlation=0.5000000000000001,pvalue=0.4999999999999999)
# encoding
print(stats.spearmanr([3,1,2,3],[3,1]))
>> SpearmanrResult(correlation=0.05555555555555556,pvalue=0.9444444444444444)
解决方法
除非数据的字母顺序等于预期顺序,否则应对变量进行编码。
在内部,SciPy正在命令您的数据进行测试。如果是整数,则它们的顺序显然等于您的数据值,例如1 < 2 < 3
。对于字符串,其顺序很可能是其字母顺序,例如a < b < c
。
您的情况是预期的订单可能是
never < sometimes < always
low < medium < high
但是,按字母顺序对这些值列表进行排序会产生(很可能是不正确的)顺序
always < never < sometimes
high < low < medium
如果您手动将此列表编码为整数或可正确排序的字符串值,则可以解决此问题:
import scipy
# Incorrect alphabetical order
scipy.stats.spearmanr(['always','never','sometimes','always'],['high','medium','low','low'])
# SpearmanrResult(correlation=0.5000000000000001,pvalue=0.4999999999999999)
# Incorrect integer order
scipy.stats.spearmanr([1,2,3,1],[1,2])
# SpearmanrResult(correlation=0.5000000000000001,pvalue=0.4999999999999999)
# Correct integer order
scipy.stats.spearmanr([3,1,3],[3,1])
# SpearmanrResult(correlation=0.05555555555555556,pvalue=0.9444444444444444)
# Correct alphabetical order
scipy.stats.spearmanr(['c','a','b','c'],['c','a'])
# SpearmanrResult(correlation=0.05555555555555556,pvalue=0.9444444444444444)