Calculate the percent change between every rolling nth row in a Pandas DataFrame

How can I calculate the percentage change between every rolling nth row in a Pandas DataFrame? Using every 2nd row as an example:

Given the following Dataframe:

>df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55], 
               "B":[5, 2, 54, 3, 2, 32],  
               "C":[20, 20, 7, 21, 8, 5], 
               "D":[14, 3, 6, 2, 6, 4]})

I would like the resulting DataFrame to be:

enter image description here

But, the closest I am getting by using this code:

>df.iloc[::2,:].pct_change(-1)

Which results in this:

enter image description here

It is performing the calculation for every other row but this is not the same as the a rolling window of calculating every nth row. I came across a similar Stack post but that example is not very straightforward.

Also, as a bonus, I'd like to display the resulting output as a percentage to two decimal places.

Thank you for your time!

Upvotes: 2

Views: 2507

Answers (1)

Got it! Use the option "periods" for 'pct_change()'.

>df.pct_change(periods=-n) #where n=2 for the given example.

Upvotes: 1

Related Questions