Home > Mobile >  Pandas DateTime index, assign value to column based on based on time AND day filter
Pandas DateTime index, assign value to column based on based on time AND day filter

Time:11-26

Im trying to assign a value to a column based on a day and time filter. Lets say I create a dataframe:

import pandas as pd
from datetime import date

date_range = pd.DataFrame({'date': pd.date_range(date(2019,8,30), date.today(), freq='15T')})
date_range.index = date_range['date']

I can then filter for the day (Sunday) and assign a value:

date_range['Happy Hour'] = ((pd.DatetimeIndex(date_range.index).dayofweek) // 6 == 'Yes!!')

and I can also filter a timeframe and assign a value

date_range.loc[date_range.between_time('15:00','18:59').index, 'Happy Hour'] = 'Yes!!'

But surely there is an easy way to combine these into one line of code so every Sunday between 15:00 and 19:00 the Happy Hour column gets filled with 'Yes!!'

CodePudding user response:

First filter Sundays and then filter times by:

idx = date_range[date_range.index.dayofweek == 6].between_time('15:00','18:59').index
date_range.loc[idx, 'Happy Hour'] = 'Yes!!'
print (date_range)
  • Related