gpt4 book ai didi

python - Pandas 成对算术类似于rolling().corr()

转载 作者:行者123 更新时间:2023-12-01 06:49:02 25 4
gpt4 key购买 nike

我有一个数据框如下:

fsym                            EOS       BTC       BNB
time
2018-11-30 00:00:00+00:00 -0.051903 -0.069088 -0.058162
2018-12-01 00:00:00+00:00 0.026936 0.044739 0.040303
2018-12-02 00:00:00+00:00 -0.034843 -0.012935 -0.005900
2018-12-03 00:00:00+00:00 -0.108108 -0.070375 -0.028180
2018-12-04 00:00:00+00:00 -0.048583 0.019509 0.131986

我可以简单地计算列成对相关性:

pt = pt.rolling(3).corr()

产生:

sym                                 EOS       BTC       BNB
time fsym
2018-11-30 00:00:00+00:00 EOS NaN NaN NaN
BTC NaN NaN NaN
BNB NaN NaN NaN
2018-12-01 00:00:00+00:00 EOS NaN NaN NaN
BTC NaN NaN NaN
BNB NaN NaN NaN
2018-12-02 00:00:00+00:00 EOS 1.000000 0.952709 0.938688
BTC 0.952709 1.000000 0.999066
BNB 0.938688 0.999066 1.000000
2018-12-03 00:00:00+00:00 EOS 1.000000 0.998738 0.969385
BTC 0.998738 1.000000 0.980492
BNB 0.969385 0.980492 1.000000
...

如何类似地计算数据帧的成对差异?我猜这相当于使用滚动窗口 1。

编辑:正如评论中所指出的,上面的示例实际上并不是我没有注意到的列相关性。

最佳答案

如果您想要 9 列:

# test data
df = pd.DataFrame(np.arange(12).reshape(-1,3), columns=list('abc'))

s = df.values
new_cols = pd.MultiIndex.from_product([df.columns, df.columns])

pd.DataFrame((s[:,None,:] - s[:, :, None]).reshape(len(df), -1),
index=df.index,
columns=new_cols)

输出:

   a        b        c      
a b c a b c a b c
0 0 1 2 -1 0 1 -2 -1 0
1 0 1 2 -1 0 1 -2 -1 0
2 0 1 2 -1 0 1 -2 -1 0
3 0 1 2 -1 0 1 -2 -1 0

关于python - Pandas 成对算术类似于rolling().corr(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com