首页 > 解决方案 > 在 Python 中估计相关性

问题描述

我有一个带有标签和用户名的数据集:

Labels   Usernames
1         Londonderry
1         Londoncalling
1          Steveonder43
0         Maryclare_re
1         Patent107391
0         Anonymous 
1         _24londonqr
... 

我需要证明包含单词 London 和标签 1 的用户名之间存在相关性。为此,我创建了第二个标签以查看单词 London 的位置

for idx, username in df['Usernames']:
    if 'London' in username:
        df['London'].iloc[idx] = 1
    else:
        df['London'].iloc[idx] = 0

然后我使用 Pearson 相关系数比较了这些二元变量:

import scipy.stats.pearsonr as rho
corr = rho(df['labels'], df['London'])

但是它不起作用。我在上述步骤中遗漏了什么吗?

标签: pythonpandasscipypearson-correlation

解决方案


Labels在你的数据框中,但你通过labels了,我也通过contains

df['London'] = df['Usernames'].str.contains('London').astype(int)
from scipy import stats
stats.pearsonr(df['Labels'], df['London'])
Out[12]: (0.4, 0.37393392381774704)

推荐阅读