Pandas滚动成对应用

klr1opcd  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(38)

我想做一件相当于

df.rolling(window).cov()

字符串
使用自定义协方差(它应该给我一个给予DataFrame(index=MultiIndex([dates, features]), columns=[features]))。
我已经尝试

df.rolling(window).apply(custom_cov)


.apply()似乎需要一个返回标量而不是矩阵的函数。
你会怎么做?

q35jwt9p

q35jwt9p1#

因此,正如所指出的,Rolling.apply在这方面是有限的,需要一个解决方案:

import numpy as np
import pandas as pd

def rolling_apply_matrix(X: pd.DataFrame, func, window: int, **kwargs):

    applied = {}
    for i, x in enumerate(X.rolling(window=window, **kwargs) start=1):
        result = func(x.T) if i >= window else np.nan
        applied[x.index[-1]] = pd.DataFrame(result, index=X.columns, columns=X.columns)

    return pd.concat(applied.values(), keys=applied.keys(), axis="index")

字符串
健全检查:

index = range(15)
columns = ["A", "B"]
X = pd.DataFrame(np.random.random(size=(len(index), len(columns))), index=index, columns=columns)

for window in [3, 5, 7]:
    rolling_cov = X.rolling(window=window).cov()
    rolling_apply_cov = rolling_apply_matrix(X=X, func=np.cov, window=window)
    are_the_same = np.all(np.isclose(
        rolling_cov,
        rolling_apply_cov,
        equal_nan=True,
    ))
    print(are_the_same)
# True
# True
# True

相关问题