adele adele - 3 months ago 6
Python Question

Function to capture change between values in different columns

Can someone please help me with a simple function to capture the change between open and Last as per the examples below:

The data:

Open High Low Last
Timestamp
2014-03-04 1783.50 1796.00 1783.50 1793.25
2014-03-05 1793.25 1796.50 1790.50 1794.00
2014-03-06 1798.00 1802.25 1795.00 1797.75
2014-03-07 1804.75 1805.50 1790.50 1798.75


Its easy enough for me to do a similar function when capturing something like the range between
High
and
Low
with:

def daily_range(df):
return df['High'] - df['Low']


But how do we do a similar function the with
Open
and
Last
?

I will use
apply
on this function to get a new column in my dataframe and desired output is shown below:

Open High Low Last Desired output
Timestamp
2014-03-04 1783.50 1796.00 1783.50 1793.25 9.75
2014-03-05 1793.25 1796.50 1790.50 1794.00 0.75
2014-03-06 1798.00 1802.25 1795.00 1797.75 -0.25


Basically if
Open
is higher than
Last
I need to do
Open
-
Last
and if
Last
is higher than
Open
I need to do
Last
-
Open
. I could do this with an
if
in the function but there must be a better way to do this simple task and I would like to find this.

Update:

Sorry if my question was not correctly worded. I did however show desired output with negative values desired output (see above).

On 2014-03-06 below the move was -0.25 but the code given in the answer shows 0.25 not -0.25. Can you help with this?

Open Last desired


Timestamp

2014-03-04 1783.50 1793.25 9.75
2014-03-05 1793.25 1794.00 0.75
2014-03-06 1798.00 1797.75 0.25

Answer
df['desired'] = (df['Open'] - df['Last']).abs()

This gives you the absolute value of the difference (if df['Last'] is greater than df['Open'], it becomes df['Last'] - df['Open'])

Your sample output is, on the other hand, is the result of df['Last'] - df['Open'], without the absolute value.

Comments