如何抵消 Pandas 与日期时间指数的 Pearson 相关性

How to Offset Pandas Pearson Correlation with Datetime Index

我正在尝试获取前一周输入与下周输出的相关值。

为了这个例子,我将其设置为每周的输入将是下一周的输出,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

此处上传了完整的示例数据: https://drive.google.com/open?id=0B4xdnV0LFZI1MzRUOUJkcUY4ajQ

到目前为止,这是我的代码:

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 选项,我不确定该怎么做。

感谢任何帮助。

谢谢, 我

如果你在一个数据帧上做.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