简体   繁体   中英

Allocating the timeframe based on the datetime using pandas

I need to find the timeframe from the master based on the input time. cust_id starttime 0 1 2000-01-01 09:00:03 1 2 2000-01-01 18:01:03

output i needed is cust_id starttime timeframe 0 1 2000-01-01 09:00:03 morning 1 2 2000-01-01 18:01:03 evening

Code for creating master timeframe details mastdf={'timeframe':['morning','latemorning','midnoon','evening'],'start_time':['8:00:00','11:00:00','13:00:00','17:00:00'],'end_time':['10:59:59','13:59:59','16:59:59','7:59:59']}enter code here

Code for creating input dataframe inputdf={'cust_id':[1,2],'starttime':['2000-01-01 09:00:03', '2000-01-01 18:01:03']}

Use cut for binning but first convert values to timedeltas by to_timedelta , create bins with add endpoint 24H and for timeframe between 00:00:00 to 8:00:00 is used fillna by last value of column timeframe :

mastdf={'timeframe':['morning','latemorning','midnoon','evening'],
        'start_time':['8:00:00','11:00:00','13:00:00','17:00:00'],
        'end_time':['10:59:59','13:59:59','16:59:59','7:59:59']}
mastdf = pd.DataFrame(mastdf)
print (mastdf)
     timeframe start_time  end_time
0      morning    8:00:00  10:59:59
1  latemorning   11:00:00  13:59:59
2      midnoon   13:00:00  16:59:59
3      evening   17:00:00   7:59:59

inputdf={'cust_id':[1,2],'starttime':['2000-01-01 09:00:03', '2000-01-01 18:01:03']}
inputdf = pd.DataFrame(inputdf)
inputdf['starttime'] = pd.to_datetime(inputdf['starttime'])

start =  pd.to_timedelta(mastdf['start_time']).tolist() + [pd.Timedelta(24, unit='h')]
s = pd.to_timedelta(inputdf['starttime'].dt.strftime('%H:%M:%S'))
last = mastdf['timeframe'].iat[-1]
inputdf['timeframe'] = pd.cut(s, 
                              bins=start, 
                              labels=mastdf['timeframe'], right=False).fillna(last)
print (inputdf)
   cust_id           starttime timeframe
0        1 2000-01-01 09:00:03   morning
1        2 2000-01-01 18:01:03   evening

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