0

I am quite new to pandas and I have a dataframe as follows,

  year  A    B
0 2000 101   20
1 2001 102   10
2 2002 103   5
3 2003 250   2
4 2004 500   4

I want to create new column ( column C) by dividing the column B row value by the row value just below it. As follows,

  year  A    B   C
0 2000 101   20  2 
1 2001 102   10  2
2 2002 103    5  2.5
3 2003 250    2  0.5
4 2004 500    4  

Not sure how to do it ( think for loop helps), Thanks

Tharindu
  • 311
  • 1
  • 2
  • 11
  • Please edit your question to be more clear. Where is your data? What is your expected output? We want to see more details in your question. Explanations aren't nearly as useful or clear as just seeing your data. Print `df.head(10)` and paste its output in your question as _text_, and I'll reopen your question. – cs95 Nov 05 '17 at 05:42
  • Thanks for your reply, I have reformatted it – Tharindu Nov 05 '17 at 06:04

1 Answers1

2

Use div + shift:

df['C'] = df.B / df.B.shift(-1)    
df

   year    A   B    C
0  2000  101  20  2.0
1  2001  102  10  2.0
2  2002  103   5  2.5
3  2003  250   2  0.5
4  2004  500   4  NaN
cs95
  • 379,657
  • 97
  • 704
  • 746