两个月前我在这里问了一个问题(Is it possible to do running correlation with one fixed series in Python?),我从一位用户那里得到了很大的帮助。
我的目标是与 Pandas 中的一个固定系列进行运行关联。这可以通过以下按行工作的代码来实现。但是,我的目标是按列执行此操作。因此,我不想逐行测试相关性,而是想为每一列运行相关性测试。任何帮助表示赞赏!
#Method to do running correlation rowwise.
import pandas as pd
from scipy.stats import pearsonr
import numpy as np
# running correlation, one fixed series (rows)
df1 = pd.DataFrame([1,3,2,4,5,6,3,4,1,2,3,2,2,3,2,5,1,2,1,2,8,8,8,8,8,8,8])
df2 = pd.DataFrame([1,2,3,2])
CORR_VALS = df2[0].values
def get_correlation(vals):
return pearsonr(vals, CORR_VALS)[0]
df1['correlation'] = df1.rolling(window=len(CORR_VALS)).apply(get_correlation)
但是,我的目标是按列执行此操作。
然后我的数据看起来像这样:
values = {'column1': [7,2,3,1],
'column2': [1,5,2,3],
"column3" : [2,5,2,5]
}
df1 = pd.DataFrame(values)
df2 = pd.DataFrame([2,3,4,3])
print(df1)
column1 column2 column3
0 7 1 2
1 2 5 5
2 3 2 2
3 1 3 5
print(df2)
0
0 2
1 3
2 4
3 3
我想要的输出是这样的:
Out[71]:
0
0 -0.620920
1 0.239046
2 0.000000