I have 2 columns in dataframe (date & sell_price). My expected output is like this. I want to add one more column named profit in dataframe that needs to be calculated by current sell_price - first sell price (stars one)
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
I know the diff in pandas that gives difference between consecutive rows. How can we achieve expected o/p with diff or any other function on pandas?
For general Index
like DatetimeIndex
use iloc
with iat
, but it working only with positions, so necessary get_loc
:
pos = df.columns.get_loc('sell_price')
df['profit'] = df.iloc[1:, pos] - df.iat[0, pos]
If default RangeIndex
use loc
with at
:
df['profit'] = df.loc[1:, 'sell_price'] - df.at[0, 'sell_price']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With