使用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

解决方法

尝试按照注释中的建议将所有数据框列更改为数字dtypes

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...