Q:

Create new column in pandas dataframe by calculation from previous index columns

Hi I am new and learning pandas for data analysis. I have 2 columns data
A   B
1   2   
2   3
3   4
4   5

I want to create a third column C which result would be calculated by column B , by subtracting upper value with current one and dividing by current.
A   B   C
1   2   
2   3   0.33
3   4   0.25
4   5   0.2

for example first row value for C column is empty because there is no value above 2 . 
0.33 = > 3 - 2 / 3 , 
0.25 = > 4 - 3 / 4 ,
0.2 = > 5 - 4 / 5 and so on

I am stuck while getting the upper value of current column. Need help how to achieve that.

A:

Use shift to shift the column and then the remaining operations are the regular ones (sub and div):
df['B'].sub(df['B'].shift()).div(df['B'])
Out: 
0         NaN
1    0.333333
2    0.250000
3    0.200000
Name: B, dtype: float64

This can also be done without chaining the methods, if you prefer.
(df['B'] - df['B'].shift()) / df['B']
Out[48]: 
0         NaN
1    0.333333
2    0.250000
3    0.200000
Name: B, dtype: float64

A:

Edit for handling NaN and decimals.
df['C'] = (1 - df.B.shift() / df.B).map(lambda x: '{0:.2f}'.format(round(x,2))).replace('nan','')

Output:
   A  B     C
0  1  2      
1  2  3  0.33
2  3  4  0.25
3  4  5  0.20

Let's simplify and use the following with shift to get the previous value:
df['C'] = 1 - df.B.shift() / df.B

Output:
   A  B         C
0  1  2       NaN
1  2  3  0.333333
2  3  4  0.250000
3  4  5  0.200000

