2

Im new to pandas and am trying to run a calculation on every row that uses the closing price from yesterday and prices from today. ie:

for 2011-07-26:
    new_column = max(df.high['2011-07-25'], df.close['2011-07-26'])

I thought about using iterating through all the rows, but thought it would be more efficient to use df.apply function. But, I cannot figure out how to access the previous days closing price from within my function.

Here is a snippet of my dataframe.

              open    high     low   close
date                                      
2011-07-22  1597.6  1607.7  1597.5  1601.5
2011-07-25  1618.2  1620.3  1609.4  1612.2
2011-07-26  1610.7  1617.5  1608.0  1616.8

whats the best way to accomplish this?

1 Answer 1

2

You could do a shift first:

In [8]: df['yesterday_high'] = df['high'].shift()

In [9]: df
Out[9]: 
              open    high     low   close  yesterday_high
date                                                      
2011-07-22  1597.6  1607.7  1597.5  1601.5             NaN
2011-07-25  1618.2  1620.3  1609.4  1612.2          1607.7
2011-07-26  1610.7  1617.5  1608.0  1616.8          1620.3

Then you can take the max of the yesterday_high and close columns:

In [11]: df[['yesterday_high', 'close']].max(axis=1)
Out[11]: 
date
2011-07-22    1601.5
2011-07-25    1612.2
2011-07-26    1620.3

In [12] df['new_col'] = df[['yesterday_high', 'close']].max(axis=1)

or alternatively:

In [13]: df.apply(lambda x: max(x['yesterday_high'], x['close']), axis=1)
Out[13]: 
date
2011-07-22    1601.5
2011-07-25    1612.2
2011-07-26    1620.3
2
  • but I wanted to take the max of todays high to yesterdays close. It looks like this is just taking the max from today's high and close.
    – CraigH
    Mar 25, 2013 at 11:15
  • @CraigH Sorry about that, I've updated, is this what you're after? Mar 25, 2013 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.