使用 scipy 的相关性

Correlation using scipy

我有两个变量,一个叫polarity,另一个叫sentiment。我想看看这两个变量之间是否存在相关性。 polarity 可以取值从 01 (连续); 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

尝试按照评论中的建议将所有数据框列更改为数字数据类型:

df = df.astype(float)

在调用 pearsonr 函数之前。

由于您正在处理 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