0

I am using the following code to apply a sliding window on time-series data. I want to set up my first window as fixed and then apply the sliding window as shown below in the desired output.

df = pd.DataFrame({'B': [0, 1, 2, 3, 4, 5, 6,7,8,9,10]})
def sliding_window(data, size):
 return [ data[x:x+size] for x in range( len(data) - size + 1 ) ]
sliding_window(df, 7)

output

[ B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6,
 B
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7,
 B
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8,
 B
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9,
 B
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
 10 10]

Desired output Example:

I am using the fixed window of size 5 here. and it always should be the first window, and the sliding window is same as before except it slides from first window. Like the left figure in the images.. enter image description here

[ B
 0 0
 1 1
 2 2
 3 3
 4 4,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9,
 B
 0 0
 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
 10 10]
asked Jun 14, 2020 at 20:45
7
  • Your desired output is not a sliding window though Commented Jun 14, 2020 at 20:48
  • Why do you think this is not a sliding window? Is the right part in the figure is a sliding window? Commented Jun 14, 2020 at 23:31
  • 1
    the right part definitely is. Looks like the left part is called "expanding window". Commented Jun 15, 2020 at 9:19
  • 1
    Your sliding_window function already implements this Commented Jun 15, 2020 at 13:40
  • 1
    Yes, absolutely correct Commented Jun 15, 2020 at 13:47

1 Answer 1

1

Try this:

def rolling_window_maybe(data, initial_size: int):
 return [ data[:initial_size + x] for x in range( len(data) - initial_size ) ]

For example:

data = [1,2,3,4]
size = 2
data[:size + 0] == [1,2]
data[:size + 1] == [1,2,3]
data[:size + 2] == [1,2,3,4]
answered Jun 14, 2020 at 21:04
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.