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

Time:12-31

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 open. 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

CodePudding user response:

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
  • Related