Home > Blockchain >  Pandas use time_between with apply lambda
Pandas use time_between with apply lambda

Time:11-14

I need to create 3 new boolean columns, in a datetime indexed dataframe, the value of which is 1 if the time of the day of each row falls

  • in the time range 8:30 - 15:00 for column "US_market"
  • in the time range 2:00 - 8:30 for column "EU_market"
  • in the time range 00:00 - 2:00 and 15:00 - 00:00 for "AS_market"

I tried to use apply/lambda in this way

df_elaborated['US_market'] = df_elaborated.apply(lambda x:  1 if x.between_time('8:30', '15:00') else 0)

but I got this error message "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." Anyway the query

df_elaborated.between_time('8:30', '15:00')

works properly. Any ideas?

CodePudding user response:

This is because apply would pass the entire column and you are trying to apply the between_time() logic to the full column instead of a value-by-value basis.

df_elaborated['US_market'] = np.where(df_elaborated.index.isin(df_elaborated.between_time('1:00','14:00').index),1,0)
  • Related