Home > Mobile >  Save a date when a condition is met
Save a date when a condition is met

Time:07-07

I would like to know how to get the first Date when the futures_price is higher that prices_df. In this case I want 2022-05-05 because 2100 > 1082.77. Once the condition is met I don't need to save more dates, so even though 2000 is also higher than 1074.52 I don't want to get '2022-05-06'.

prices_df = [1106, 1098, 1090.625, 1082.577, 1074.52]
future_dates = {'Date': ['2022-05-02', '2022-05-03', '2022-05-04', '2022-05-05', '2022-05-06'],
                'High': [1020, 1005, 966, 2100, 2000],
                }
future_prices = pd.DataFrame(future_dates)
future_prices = future_prices.set_index('Date')


df3.loc[i, 'Break_date'] = future_dates['Date'] if future dates > prices_df

This last line should save in df3, break_date column the previous date '2022-05-05'. Only 1 date.

thank you!

CodePudding user response:

You could do it like this:

future_prices.loc[future_prices['High'] > prices_df].index[0]

Result

'2022-05-05'

You would need to add additional error checking to handle the situation where the condition was not met.

Handling the situation where the condition was not met

msk = future_prices['High'] > prices_df
future_prices.loc[msk].index[0] if msk.any() else 0

else 0 could be else whatever depending on your application.

  • Related