freevillage
freevillage

Reputation: 1

Rolling multidimensional function in pandas

Let's say, I have the following code.

import numpy as np
import pandas as pd

x = pd.DataFrame(np.random.randn(100, 3)).rolling(window=10, center=True).cov()

For each index, I have a 3x3 matrix. I would like to calculate eigenvalues and then some function of those eigenvalues. Or, perhaps, I might want to compute some function of eigenvalues and eigenvectors. The point is that if I take x.loc[0] then I have no problem to compute anything from that matrix. How do I do it in a rolling fashion for all matrices?

Thanks!

Upvotes: 0

Views: 330

Answers (1)

Sumanth
Sumanth

Reputation: 507

You can use the analogous eigenvector/eigenvalue methods in spicy.sparse.linalg.

import numpy as np
import pandas as pd
from scipy import linalg as LA

x = pd.DataFrame(np.random.randn(100, 3)).rolling(window=10, center=True).cov()
for i in range(len(x)):
    try:
        e_vals,e_vec = LA.eig(x.loc[i])
        print(e_vals,e_vec)
    except:
        continue

If there are no NaN values present then you need not use the try and except instead go for only for loop.

Upvotes: 1

Related Questions