首页 > 解决方案 > 使用 scipy 的相关性

问题描述

我有两个变量,一个叫polarity,另一个叫sentiment。我想看看这两个变量之间是否存在相关性。 polarity可以取值 from01(连续);sentiment可以取值-1, 01。我试过如下:

from scipy import stats

pearson_coef, p_value = stats.pearsonr(df['polarity'], df['sentiment']) 
print(pearson_coef)

但我收到以下错误:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

值示例:

polarity      sentiment
 
0.34            -1
0.12            -1
0.85             1
0.76             1
0.5              0
0.21             0

标签: pythonpandasscipypearson-correlation

解决方案


由于您正在处理 a dataframe,因此您可以执行以下操作来了解dtypes列的 :

>>> df.info() 

 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   polarity   6 non-null      float64
 1   sentiment  6 non-null      object 

>>> df['sentiment'] = df.sentiment.map(float) # or do : df = df.astype(float)

>>> df.info()

 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   polarity   6 non-null      float64
 1   sentiment  6 non-null      float64


>>> pearson_coef, p_value = stats.pearsonr(df['polarity'], df['sentiment']) 
>>> print(pearson_coef)
0.870679269711991

# Moreover, you can use pandas to estimate 'pearsonr' correlation matrix if you want to:
>>> df.corr()

           polarity  sentiment
polarity   1.000000   0.870679
sentiment  0.870679   1.000000


推荐阅读