简体   繁体   中英

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

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!!'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM