如何从连续的行中查找利润或亏损百分比

How to find profit or loss percentage from consecutive rows

我需要帮助计算 profit/loss 百分比。我有一个数据框如下

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

我需要在数据框中添加一个新列来计算连续行的盈亏百分比,例如

Date         Price    Prof/Loss
2017-5-20    50       0
2017-5-20    60       16.66
2017-5-20    45      -23.07
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

首先,我认为您计算 Loss/Profit 的数学有误,希望我已为您修正。

其次,您可以使用.shift()方法获取上一行,使用.shift(-1)获取下一行。