r - Taking inverse of certain rows in dataframe -
i have dataframe of market trades , need multiply put returns -1. have code that, can't figure out how assign without affecting calls.
input df:
date type stock_open stock_close stock_roi 0 2016-04-27 call 5.33 4.80 -0.099437 1 2016-06-03 put 4.80 4.52 -0.058333 2 2016-06-30 call 4.52 5.29 0.170354 3 2016-07-21 put 5.29 4.84 -0.085066 4 2016-08-08 call 4.84 5.35 0.105372 5 2016-08-25 put 5.35 4.65 -0.130841 6 2016-09-21 call 4.65 5.07 0.090323 7 2016-10-13 put 5.07 4.12 -0.187377 8 2016-11-04 call 4.12 4.79 0.162621
code:
flipped_puts = trades_df[trades_df['type']=='put']['stock_roi']*-1 trades_df['stock_roi'] = flipped_puts
output of flipped puts:
1 0.058333 3 0.085066 5 0.130841 7 0.187377
output of original df:
date type stock_open stock_close stock_roi 0 2016-04-27 call 5.33 4.80 nan 1 2016-06-03 put 4.80 4.52 0.058333 2 2016-06-30 call 4.52 5.29 nan 3 2016-07-21 put 5.29 4.84 0.085066 4 2016-08-08 call 4.84 5.35 nan 5 2016-08-25 put 5.35 4.65 0.130841 6 2016-09-21 call 4.65 5.07 nan 7 2016-10-13 put 5.07 4.12 0.187377 8 2016-11-04 call 4.12 4.79 nan
try
trades_df.loc[trades_df.type.eq('put'), 'stock_roi'] *= -1
or
trades_df.update(trades_df.query('type == "put"').stock_roi.mul(-1))
both give you
trades_df
Comments
Post a Comment