python - 使用 scipy 的相关性
问题描述
我有两个变量,一个叫polarity
,另一个叫sentiment
。我想看看这两个变量之间是否存在相关性。
polarity
可以取值 from0
到1
(连续);sentiment
可以取值-1, 0
和1
。我试过如下:
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
解决方案
由于您正在处理 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
推荐阅读
- sql - APACHE IGNITE:对具有不同缓存的表进行联接查询
- r - 选择变量中出现频率最高的 n 个值
- opc-ua - 强制性 OPC-UA 服务
- php - 使用 CURL PHP 将令牌 ID 从一个 API 传递到另一个 API
- c# - 我怎样才能分布式地更新我的程序?
- joomla3.0 - 将数据库中的值调用到 Javascript 中
- vue.js - 如何从另一个 Vuex 数据属性访问 Vuex 数据属性?
- gtktreeview - gtkmm 树就像 win32 中的一棵树
- java - 在运行时使用 Appium 从一个混合应用程序切换到另一个混合应用程序
- c# - MVC JQgrid 不显示在网页上