Venkatachalam
Venkatachalam

Reputation: 16966

Ensuring constant window size in pandas rolling window function

A some custom operation needs to be done on each rolling window of size 2 in a dataframe. But rolling function in pandas, returns an output with initial window location with 1 element as well. I tried setting the min_periods, but does not help here.

df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})

for pairs in df.rolling(2, min_periods=2):
    print(pairs)

     B
0  0.0
     B
0  0.0
1  1.0
     B
1  1.0
2  2.0
     B
2  2.0
3  NaN
     B
3  NaN
4  4.0

Also indexing doesn't work for rolling function. Getting the following error for df.rolling(2)[1:]

TypeError: unhashable type: 'slice'

Upvotes: 3

Views: 526

Answers (1)

Stef
Stef

Reputation: 30579

You could use numpy's sliding_window_view

np.lib.stride_tricks.sliding_window_view(df.B, 2)

array([[ 0.,  1.],
       [ 1.,  2.],
       [ 2., nan],
       [nan,  4.]])

Upvotes: 4

Related Questions