使用熊猫datetime inot对数据进行分组,第二天的上午7点至下午7点和第二天晚上7点至上午7点分别为12小时

问题描述

我有一个具有两列的数据熊猫数据框。它有一个名为“ DateAndTime”的列(datetime64 [ns]) 还有一个名为“完成”(布尔)的列。有大约5000多个行,它们的日期和时间都不同,并且“完成”列为True。

要做的是将数据分为7 am-7pm和7 pm-7am的“班次”,并总结在12小时内发生了多少真实情况。

df.head()

DateAndTime                   Finished
109 2020-07-28 14:36:07.983     True
110 2020-07-28 14:36:34.547     True
111 2020-07-28 14:39:38.187     True
112 2020-07-28 14:41:10.547     True
113 2020-07-28 14:41:32.250     True

df.describe()

       DateAndTime                    Finished
count   5915                            5915
unique  5915                            2
top     2020-07-29 07:34:25.360000      True
freq    1                               5914
first   2020-07-28 14:36:07.983000      NaN
last    2020-08-05 04:57:10.657000      NaN

解决方法

您应该尝试这个

import numpy as np

#in case columns are in String Format 
df = df.astype({'DateAndTime': np.datetime64,'Finished':np.bool}) 

# 7AM : 7PM Shift
shift_1 = df[df.DateAndTime.apply(lambda t: (t.hour in range(7,19)) or (t.hour==19 and (t.second+t.minute==0)))]

# 7PM : 7AM Shift
shift_2 = df[df.DateAndTime.apply(lambda t: not ((t.hour in range(7,19)) or (t.hour==19 and (t.second+t.minute==0))))]

shift_1_TruedCount = shift_1.Finished.to_list().count(True)
shift_2_TruedCount = shift_2.Finished.to_list().count(True)

print(shift_1_TruedCount,shift_2_TruedCount)

,

假设您的DateAndTime列已为Timestamp类型:

# Move DateAndTime back by 7 hours
# Now shift 1 is 0:00 to 12:00,shift 2 is 12:00 - 24:00
h = (df['DateAndTime'] - pd.Timedelta(hours=7)).dt.hour < 12
df['Shift'] = h.map({True: '7am-7pm',False: '7pm-7am'})