How to calculate diff between previous rows and new rows for different columns

Question:

I have a df as follows

index open close
       10  12
       15  16
       20   19

To find diff between previous row of one column, we can use

df['diff] = df['close'].diff()

But i want to find diff between current open and previous close. How can i do it?

index open close diff_new_open_prev_close
       10  12.    Nan
       15  16.    3
       20   19.   4

diff = current rows open - prev rows close
Asked By: user93796

||

Answers:

You can use pandas.DataFrame.shift.

df['prev_close'] = df['close'].shift()
df['diff_new_open_prev_close'] =  df['open'] - df['prev_close']
print(df)

# Or 
df['diff_new_open_prev_close'] = df['open'].subtract(df['close'].shift())

Output:

   open  close  prev_close  diff_new_open_prev_close
0    10     12         NaN                       NaN
1    15     16        12.0                       3.0
2    20     19        16.0                       4.0
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.