如何获取pandas中第一行和当前行之间的差异

Dev*_*wal 3 python pandas

我在数据框中有 2 列(日期和销售价格)。我的预期输出是这样的。我想在数据框中添加一个名为利润的列,该列需要通过当前的销售价格计算 - 第一个销售价格(星级一)

        date            sell_price  profit(needs to be added)
    0   2018-10-26       **21.20**    NaN
    1   2018-10-29       15.15      -6.05
    2   2018-10-30       15.65      -5.55
    3   2018-10-31        0.15     -21.05
    4   2018-11-01        5.20     -16.00
Run Code Online (Sandbox Code Playgroud)

我知道熊猫中的差异会导致连续行之间的差异。我们如何在 Pandas 上使用 diff 或任何其他函数实现预期的 o/p?

jez*_*ael 7

对于一般Index喜欢DatetimeIndex使用ilociat,但只使用了位置,因此必要的get_loc

pos = df.columns.get_loc('sell_price')
df['profit'] =  df.iloc[1:, pos] - df.iat[0, pos]
Run Code Online (Sandbox Code Playgroud)

如果默认RangeIndex使用loc具有at

df['profit'] =  df.loc[1:, 'sell_price'] - df.at[0, 'sell_price']
Run Code Online (Sandbox Code Playgroud)
print (df)
         date  sell_price  profit
0  2018-10-26       21.20     NaN
1  2018-10-29       15.15   -6.05
2  2018-10-30       15.65   -5.55
3  2018-10-31        0.15  -21.05
4  2018-11-01        5.20  -16.00
Run Code Online (Sandbox Code Playgroud)