简体   繁体   中英

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'

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.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM