2

I have a dataframe of 10 observations. I'd like to divide row 1 by row 2, row 2 by row 3, row 3 by row 4, etc. When I get to row 10, then I want to divide row 10 by row 1.

Here is some sample code:

import pandas as pd
dict1 = {'group':[1,2,3,4,5,6,7,8,9,10]
        ,'value': [.35,.41,.40,.60,.36,.55,.49,.57,.57,.52]}
df = pd.DataFrame(dict1)

Here is the result I'm looking for:

dict1 = {'group':[1,2,3,4,5,6,7,8,9,10]
        ,'value': [.35,.41,.40,.60,.36,.55,.49,.57,.57,.52]
        , 'target': [.854,1.025,.667,1.667,.655,1.122,.860,1,1.096,.673]}
df = pd.DataFrame(dict1)
Jordan
  • 1,415
  • 3
  • 18
  • 44

1 Answers1

0

You can access previous / next elements of a column using shift, but here there is a exception for the last element (divide by the first row).

So here you can use Numpy function named roll, performing "rotation" or circular shift of your column.

To perform your operation, run:

df['target'] = df.value / np.roll(df.value, shift=-1)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41