I want to get the relative index of a column in a pandas frame

I want to make a new 5-day return column for a stock, so to speak. I am using pandas dataframe. I have calculated the moving average using the roll_mean function, but I'm not sure how to refer to rows, such as a table (B6-B1). Does anyone know how I can make this link and subtract the index?

sample data frame:

day    price    5-day-return
1      10          -
2      11          -
3      15          -
4      14          -
5      12          -
6      18          i want to find this ((day 5 price) -(day 1 price) )
7      20          then continue this down the list
8      19
9      21 
10     22

      

+3


source to share


1 answer


You need the following:

In [10]:

df['5-day-return'] = (df['price'] - df['price'].shift(5)).fillna(0)
df
Out[10]:
   day  price  5-day-return
0    1     10             0
1    2     11             0
2    3     15             0
3    4     14             0
4    5     12             0
5    6     18             8
6    7     20             9
7    8     19             4
8    9     21             7
9   10     22            10

      



shift

returns a string at a specific offset, we use that to subtract from the current string. fillna

fills in the values NaN

to be executed before the first valid calculation.

+3


source







All Articles