Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add part_of_the_day from time column given (first shift, second shift, dead time)

I want to add shift names from time column in my dataset.

7:00:00 to 17:00:00 (same day) - First Shift
17:00:01 to 4:00:00 (next morning) - Second Shift
4:00:01 to 6:59:59 (same morning) - Dead Time

I followed some given solutions form stack overflow but in vain.
Glimpse of the dataset

    Date    Time    
    2022-04-13  16:57:00        
    2022-09-07  10:46:00    
df = pd.DataFrame({'Time':range(1, 25)})

b = [4,7,17,24]
l = ['Dead Time', 'First Shift','Second Shift']
df['Shifts'] = pd.cut(df['Time'], bins=b, labels=l, include_lowest=True)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

# define bins
b=[0, 3, 6, 16, 24]

# define labels
l = ['Second Shift','Dead Time', 'First Shift','Second Shift']

# capture the hour from the Time and then label using pd.cut
df['shift']=pd.cut( pd.to_datetime (df['Time']).dt.hour,
      bins=b,
      labels=l,
      ordered=False)
df

Date    Time    shift
0   2022-04-13  01:57:00    Second Shift
1   2022-09-07  02:46:00    Second Shift
2   2022-04-13  04:57:00    Dead Time
3   2022-04-13  05:57:00    Dead Time
4   2022-04-13  07:57:00    First Shift
5   2022-04-13  10:57:00    First Shift
6   2022-04-13  12:57:00    First Shift
7   2022-04-13  17:57:00    Second Shift
8   2022-04-13  19:57:00    Second Shift
9   2022-04-13  22:57:00    Second Shift


in case if you shift is ending at the top of the hour at 00 minutes, shift time by 1 minute and above bins will work, without the need of looking into minutes

df['shift']=pd.cut( (pd.to_datetime (df['Time'])  + pd.offsets.Minute(-1)) .dt.hour,
      bins=b,
      labels=l,
      ordered=False)
df
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading