Dividing 24h into working shifts in Python Pandas
I am dealing with dividing a day into working shifts. Let's have a look at my sample code:
I'd like to divide the time into 3 shifts, 00:00 to 08:00 is Shift1, 08:00 to 16:00 will be Shift2 and till 00:00 will be Shift3.
What I get is true, but I would like to know if there is any elegant and easier way to do it?
In: import pandas as pd data = [['24.12.2020 05:17:32', 6], ['24.12.2020 07:20:06', 5], ['24.12.2020 09:33:29', 9],['24.12.2020 14:21:54', 12], ['24.12.2020 18:52:01', 11],['24.12.2020 22:05:19', 4]] df = pd.DataFrame(data, columns = ['DateTime', 'Counter']) print(df)
the dataframe looks like:
Out: DateTime Counter 0 24.12.2020 05:17:32 6 1 24.12.2020 07:20:06 5 2 24.12.2020 09:33:29 9 3 24.12.2020 14:21:54 12 4 24.12.2020 18:52:01 11 5 24.12.2020 22:05:19 4
In: df['DateTime'] = pd.to_datetime(df['DateTime']) df['Hour'] = df['DateTime'].dt.hour df['Hour'] = pd.to_numeric(df['Hour'],downcast="float") df['Shift1'] = (df['Hour']<8) df['Shift2'] = (df['Hour']>=8) & (df['Hour']<16) df['Shift3'] = (df['Hour']>=16) df['Shift1'] = df['Shift1'].astype(int) df['Shift2'] = df['Shift2'].astype(int) df['Shift3'] = df['Shift3'].astype(int) df['Shift1'] = df['Shift1'].replace([1,0], ['Shift1','']) df['Shift2'] = df['Shift2'].replace([1,0], ['Shift2','']) df['Shift3'] = df['Shift3'].replace([1,0], ['Shift3','']) df['SHIFTS'] = df['Shift1']+df['Shift2']+df['Shift3'] print(df)
Out: DateTime Counter Hour Shift1 Shift2 Shift3 SHIFTS 0 2020-12-24 05:17:32 6 5.0 Shift1 Shift1 1 2020-12-24 07:20:06 5 7.0 Shift1 Shift1 2 2020-12-24 09:33:29 9 9.0 Shift2 Shift2 3 2020-12-24 14:21:54 12 14.0 Shift2 Shift2 4 2020-12-24 18:52:01 11 18.0 Shift3 Shift3 5 2020-12-24 22:05:19 4 22.0 Shift3 Shift3
Solution 1:
Try to create SHIFTS
column before then pivot your dataframe:
df['SHIFTS'] = df['DateTime'].astype('datetime64').dt.hour \
.floordiv(8).add(1).astype(str).radd('shift')
df = df.join(df.reset_index().pivot('index', 'SHIFTS', 'SHIFTS')).fillna('')
Output:
>>> df
DateTime Counter SHIFTS shift1 shift2 shift3
0 24.12.2020 05:17:32 6 shift1 shift1
1 24.12.2020 07:20:06 5 shift1 shift1
2 24.12.2020 09:33:29 9 shift2 shift2
3 24.12.2020 14:21:54 12 shift2 shift2
4 24.12.2020 18:52:01 11 shift3 shift3
5 24.12.2020 22:05:19 4 shift3 shift3