Pandas 中两个系列之间的相关性

问题描述 投票:0回答:1

我试图找到两个不同长度的 Pandas 系列之间的相关性,但它没有给我预期的答案。

这是我尝试过的。我有两个数据框 A 和 B,其中包含“时间”和“值”列。 “time”是以“2023-08-18”结束,但在 A 和 B 中的不同日期开始的日期(具体来说,分别为“2020-05-11”和“2017-10-24”)。我创造了

A_series = A.loc[:,'time']

B_series = B.loc[:,'time']

并尝试使用

A_series.corr(B_series, method = 'pearson')

但没有得到正确答案。通过在 Excel 中绘制和使用 =CORREL,我知道相关性应该在 0.97 左右,但 Pandas 给了我 0.045。

由于问题可能是两个时间段不匹配,因此我尝试按“时间”列(降序)对 A 和 B 进行排序,然后再次使用 Series.corr 计算相关性,但得到了相同的答案。

对于我的下一次尝试,我可能会尝试创建一个包含“time”、“values_A”、“values_B”列的新数据框,其中“time”仅包括 A 和 B 中较短的周期。但我很好奇为什么会出现上述情况发生了。对于这个相当简单的问题表示歉意。我今天早上刚刚开始学习 Pandas。

python pandas correlation
1个回答
0
投票
import pandas as pd
import numpy as np

# Here I created a date range for A from '2020-05-11' to '2023-08-18'
dates_A = pd.date_range(start='2020-05-11', end='2023-08-18')
values_A = np.random.rand(len(dates_A))
A = pd.DataFrame({
    'time': dates_A,
    'values': values_A
})

# And here I did the same for B with different range
dates_B = pd.date_range(start='2017-10-24', end='2023-08-18')
values_B = np.random.rand(len(dates_B))
B = pd.DataFrame({
    'time': dates_B,
    'values': values_B
})

# I made the column 'time' as index
A.set_index('time', inplace=True)
B.set_index('time', inplace=True)

# Merged both A and B on the 'time' index
merged_df = A.merge(B, left_index=True, right_index=True, suffixes=('_A', '_B'))

# and finally I calculated the correlation between 'values_A' and 'values_B'
correlation = merged_df['values_A'].corr(merged_df['values_B'], method='pearson')

print("Correlation:", correlation)
© www.soinside.com 2019 - 2024. All rights reserved.