我有一个这样的数据集
index Date_Time Pass_ID El
0 3/30/23 05:12:36.36 A 1
1 3/30/23 05:12:38.38 A 2
1 3/30/23 05:12:40.40 A 3
1 3/30/23 05:12:42.42 A 4
1 3/30/23 05:12:44.44 A 4
1 3/30/23 12:12:50.50 B 3
1 3/30/23 12:12:52.52 B 4
1 3/30/23 12:12:54.54 B 5
1 3/30/23 12:12:56.56 B 6
1 3/30/23 12:12:58.58 B 7
1 3/30/23 12:13:00.00 B 8
1 3/30/23 12:13:02.02 B 9
1 3/31/23 20:02:02.02 C 3
1 3/31/23 20:02:05.05 C 4
Date_Time 是 pandas 日期时间对象。
我想按
Pass_ID
对记录进行分组,然后 然后仅选择当天特定时间之间发生的唯一 Pass_ID:例如,10:00 到 13:00 之间将返回 B。
我不知道如何让 groupby 和 ' Between_time' 在这种情况下工作......这似乎是最好的前进方式。在将 Date_Time 设置为索引后,我还尝试使用 lambda 函数,但这不起作用。使用聚合似乎不允许我提取 Date_Time 字段的 dt.hour 。有人知道如何简洁地做到这一点吗?
尝试:
# to datetime if necessary
# df["Date_Time"] = pd.to_datetime(df["Date_Time"])
out = df.set_index("Date_Time").between_time("10:00", "13:00")["Pass_ID"].unique()
print(out)
打印:
['B']