Python 如何用Datetime索引抵消Pearson相关性
我试图获得前一周输入与下一周输出的相关值 在本例中,我将其设置为每周的输入将是下周的输出,Python 如何用Datetime索引抵消Pearson相关性,python,python-3.x,pandas,pearson-correlation,Python,Python 3.x,Pandas,Pearson Correlation,我试图获得前一周输入与下一周输出的相关值 在本例中,我将其设置为每周的输入将是下周的输出,df.corr()应该给出1.000000的结果 我的原始数据如下所示: Date Input Output 1/1/2010 73 73 1/7/2010 2 73 1/13/2010 3 2 1/19/2010 4 3 完整样本数据上传至此处: 以下是我目前的代码: import pand
df.corr()
应该给出1.000000
的结果
我的原始数据如下所示:
Date Input Output
1/1/2010 73 73
1/7/2010 2 73
1/13/2010 3 2
1/19/2010 4 3
完整样本数据上传至此处:
以下是我目前的代码:
import pandas as pd
df = pd.read_csv('pearson.csv')
df['Date'] = pd.to_datetime(df['Date'], errors = 'coerce')
df = df.set_index(pd.DatetimeIndex(df['Date']))
df = df[['Input', 'Output']]
x = df.corr(method = 'pearson', min_periods=1)
print(x)
作为一个新手,我被困在这里。我没有看到函数中内置的shift
选项,也不知道如何执行此操作
非常感谢您的帮助
谢谢,,
Me如果对数据帧执行
.corr
,它将生成相关矩阵
在您的例子中,您只需要两个时间序列之间的相关性,您可以使用下面的代码实现这一点。请注意,时间序列的.corr
方法需要参数other
,该参数是用于计算相关性的序列
df["Input"].corr(df["Output"].shift(-1), method = 'pearson', min_periods = 1) #1
如果需要相关矩阵,则应首先创建具有移位输出的数据帧,然后计算相关性:
temp_df = pd.concat([df['Input'], df['Output'].shift(-1)], axis = 1).dropna()
temp_df.corr(method = 'pearson', min_periods = 1)
# Input Output
#Input 1.0 1.0
#Output 1.0 1.0
如果对数据帧执行
.corr
,它将生成一个相关矩阵
在您的例子中,您只需要两个时间序列之间的相关性,您可以使用下面的代码实现这一点。请注意,时间序列的.corr
方法需要参数other
,该参数是用于计算相关性的序列
df["Input"].corr(df["Output"].shift(-1), method = 'pearson', min_periods = 1) #1
如果需要相关矩阵,则应首先创建具有移位输出的数据帧,然后计算相关性:
temp_df = pd.concat([df['Input'], df['Output'].shift(-1)], axis = 1).dropna()
temp_df.corr(method = 'pearson', min_periods = 1)
# Input Output
#Input 1.0 1.0
#Output 1.0 1.0
与1k;)一致与1k;)一致顺便说一句,每6天一次。