如何在python中测试两个集合之间的相关性?

2024-06-15 02:58:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的数据帧,其中一个如下所示

df1=

      Datetime      BSL
0          7  127.504505
1          8  115.254132
2          9  108.994275
3         10  102.936860
4         11   99.830400
5         12  114.660522
6         13  138.215339
7         14  132.131075
8         15  121.478006
9         16  113.795645
10        17  114.038462

另一个是df2=

    Datetime       Number of Accident
0          7                  3455
1          8                 17388
2          9                 27767
3         10                 33622
4         11                 33474
5         12                 12670
6         13                 28137
7         14                 27141
8         15                 26515
9         16                 24849
10        17                 13013

基于时间的第一个人群血糖水平(7表示上午7点到8点之间) 第二个是这两次之间的事故数量

当我尝试使用此代码时

df1.corr(df2, "pearson")

我犯了一个错误:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我怎样才能解决它?或者,我如何测试两个不同变量之间的相关性


Tags: of数据代码number数量datetime时间水平
3条回答

由于数据帧有多个列,因此需要指定要使用的列的名称:

df1['BSL'].corr(df2['Number of Accident'], "pearson")
from scipy.stats import pearsonr
df_full = df1.merge(df2,how='left')
full_correlation = pearsonr(df_full['BSL'],df_full['Accidents'])
print('Correlation coefficient:',full_correlation[0])
print('P-value:',full_correlation[1])

输出:

(-0.2934597230564072, 0.3811116115819819)
Correlation coefficient: -0.2934597230564072
P-value: 0.3811116115819819

编辑:

您需要每小时的相关性,但在数学上是不可能的,因为每小时只有1个x-y值。因此,输出将充满NAN。这是代码,但输出无效:

df_corr = df_full.groupby('Datetime')['BSL','Accidents'].corr().drop(columns='BSL').drop('Accidents',level=1).rename(columns={'Accidents':'Correlation'})
print(df_corr)

输出:

              Correlation
Datetime                 
7        BSL          NaN
8        BSL          NaN
9        BSL          NaN
10       BSL          NaN
11       BSL          NaN
12       BSL          NaN
13       BSL          NaN
14       BSL          NaN
15       BSL          NaN
16       BSL          NaN
17       BSL          NaN

熊猫数据帧的corr()方法为一个数据帧中的所有列计算相关矩阵。您有两个数据帧,因此该方法无法工作。您可以通过执行以下操作来解决此问题:

df1['number'] = df2['Number of Accident']
df1.corr("pearson")

相关问题 更多 >