Arnold Klein
Arnold Klein

Reputation: 3086

Rolling window from time-series

I am wondering if there is a simple and neat way to create a rolling window representation from a time-series data, using Pandas (etc)?

For example, consider the following Series object:

x = pd.Series(np.linspace(0,10,100))
df_wind = pd.DataFrame(roll_wind_func(x, wind_size=5))
Out: 
           0         1         2         3             4
0   0.000000  0.324699  0.614213  0.837166  9.694003e-01
1   0.324699  0.614213  0.837166  0.969400  9.965845e-01
2   0.614213  0.837166  0.969400  0.996584  9.157733e-01
3   0.837166  0.969400  0.996584  0.915773  7.357239e-01
4   0.969400  0.996584  0.915773  0.735724  4.759474e-01
5   0.996584  0.915773  0.735724  0.475947  1.645946e-01
6   0.915773  0.735724  0.475947  0.164595 -1.645946e-01
7   0.735724  0.475947  0.164595 -0.164595 -4.759474e-01
8   0.475947  0.164595 -0.164595 -0.475947 -7.357239e-01
9   0.164595 -0.164595 -0.475947 -0.735724 -9.157733e-01
10 -0.164595 -0.475947 -0.735724 -0.915773 -9.965845e-01
11 -0.475947 -0.735724 -0.915773 -0.996584 -9.694003e-01
12 -0.735724 -0.915773 -0.996584 -0.969400 -8.371665e-01
13 -0.915773 -0.996584 -0.969400 -0.837166 -6.142127e-01
14 -0.996584 -0.969400 -0.837166 -0.614213 -3.246995e-01
15 -0.969400 -0.837166 -0.614213 -0.324699 -2.449294e-16 

I have implemented (though ugly) the roll_wind_func(data=, wind_size=), but I'm wondering if Pandas offers a simpler solution (without loops)

Upvotes: 2

Views: 691

Answers (1)

IanS
IanS

Reputation: 16251

How about:

pd.DataFrame({i: x.shift(-i) for i in range(5)}).dropna()

Upvotes: 3

Related Questions