Skip to content
Advertisement

Using a for loop index in .loc to access a rolling slice of a dataframe?

I want to create rolling slices of a master dataframe. I’m trying to measure the difference in outcomes over rolling periods. The master dataframe has 120 years of data and I want to create rolling slices of 10 years of a column(s), i.e slice one goes from year 1 to 10, slice 2 goes from year 2 to 11, etc…

I’m trying to create one slice dataframe that contains all the slices, 12 rolling 10 year periods in my example.

I’m trying to do it in a for loop like this:

JavaScript

So, the first run through this should give me row 0 to 9 of master _df in the 10 rows of slice_df. The second time through the loop should give me row 1 to 10 of master_df in the 10 rows of slice_df.

I keep getting a ValueError: Length of values does not match length of index. Can I use the index of a for loop in .loc like this? Is there a better approach to this?

If I do the steps in sequential order outside a for loop it works.

JavaScript

So, it’s something I’m doing in the for loop.

Advertisement

Answer

One option is to iterate over the output of rolling.

JavaScript

will give you e.g.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement