Pyt*_*_DK 1 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
Run Code Online (Sandbox Code Playgroud)
完整示例数据在此处上传: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)
Run Code Online (Sandbox Code Playgroud)
而作为一个新手在这里,我被卡住了.我没有看到shift函数中内置的选项,也不确定如何执行此操作.
任何和所有的帮助表示赞赏.
谢谢你,我
如果.corr对数据帧进行处理,则会生成相关矩阵.
在您的情况下,您只需要两个时间序列之间的相关性,您可以使用下面的代码实现此目的.请注意,.corr时间序列的方法需要参数other,该参数是用于计算相关性的系列.
df["Input"].corr(df["Output"].shift(-1), method = 'pearson', min_periods = 1) #1
Run Code Online (Sandbox Code Playgroud)
如果您想要相关矩阵,则应首先创建一个具有移位输出的数据帧,然后计算相关性:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1214 次 |
| 最近记录: |