Find a date in pd dataframe that matches a date in a given list

Viewed 89
breakout_candles= []
for _,breakout in btc_breakouts:
    breakout_candles.append(breakout)
print(breakout_candles)

output:

 [Timestamp('2021-10-28 04:00:00+0000', tz='UTC'), Timestamp('2021-10-28 08:00:00+0000', tz='UTC'), Timestamp('2021-10-29 08:00:00+0000', tz='UTC'), Timestamp('2021-10-31 16:00:00+0000', tz='UTC'), Timestamp('2021-11-01 04:00:00+0000', tz='UTC')]

Now im trying to set a value to 1 if the date was found in breakout_candles otherwise -1:

 df['BTCgtRES'] = np.where((df['date'] in breakout_candles),1,-1)

but i m getting the ambiguous error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

i also tried this, it compiles but does nothing it has to do:

df['BTCgtRES'] = np.where((df['date'].eq (breakout in breakout_candles)),1,-1)
2 Answers

You can try with
df["BTCgtRES"] = df["date"].apply(lambda x: 1 if x in breakout_candles else -1).
Please be aware that searching in the list at each iteration might be computationally expensive, so you might want to use dict instead as a simple enough alternative.

You can try using isin() instead of in

 df['BTCgtRES'] = np.where((df['date'].isin(breakout_candles)),1,-1)
Related