微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用scipy进行相关

如何解决使用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。