-6

I need a help in calculating profit/loss percentage. I have a data frame as follows

Date         Price    
2017-5-20    50    
2017-5-20    60
2017-5-20    45

I need a new column in dataframe which calculates profit or loss percentage of consecutive rows, such as

Date         Price    Prof/Loss
2017-5-20    50       0
2017-5-20    60       16.66
2017-5-20    45      -23.07
Chris
  • 29,127
  • 3
  • 28
  • 51

1 Answers1

1
df = pd.DataFrame()
df['Date'] = ['2017-05-20', '2017-05-20', '2017-05-20']
df['Price'] = [50, 60, 45]
df['Prof/Loss'] = (df['Price'] / df['Price'].shift())*100 - 100

First, I think your math for calculating the Loss/Profit was wrong, I hope I fixed that for you.

Second, you can use the .shift() method to get the previous row, use .shift(-1) to get the next row.

dustin-we
  • 498
  • 2
  • 7