A.McCann
A.McCann

Reputation: 35

Add column to pandas df which is equal to another column, but different row

I am trying to add a column to a df which is equal to another column, but the row above. I have a column representing the percentage change in a given day, and I want to add another column which has the percentage change of the two previous days also.

This is the code I used to get the "% change" column

tickerDf['Date'] = pd.to_datetime(tickerDf['Date'])
Close = tickerDf['Close'].shift()
tickerDf['% change'] = np.where(
    tickerDf['Date'].dt.day.diff().gt(0), ((tickerDf['Open'] - Close) / Close) * 100, '')

This image indicates what I am trying to achieve.

Upvotes: 2

Views: 33

Answers (1)

SeaBean
SeaBean

Reputation: 23217

You can create the new column after setting up tickerDf['% change'] by using .shift(), as follows:

tickerDf['% change-1'] = tickerDf['% change'].shift(1) 

Upvotes: 1

Related Questions