Pob Livsig
Pob Livsig

Reputation: 105

How to divide a row by the contents of the previous row with using loops

Using a pandas DataFrame, I would like to take every ith row and divide it by the i-1th row. I would like to use vectorization (i.e., no for loops).

e.g. If I have the following DataFrame:

1      10  
2      20  
8      160  
32     480 

I would end up with:

1      10   
2       2   
4       8  
4       3

N.B. The division operations use the old table values, not the updated ones.

P.S. Sorry about the bad formatting!

Upvotes: 3

Views: 1370

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Use, div, shift, and fillna:

df.div(df.shift(1)).fillna(df).astype(int)

Output:

   A   B
0  1  10
1  2   2
2  4   8
3  4   3

Upvotes: 7

Related Questions