3

我有一个 pandas DatetimeIndex ,我想按照星期几和一天中的小时与列表匹配的标准过滤索引。例如,我有一个元组列表,表示每个时间戳的有效(星期几、小时、分钟):

[(4, 6), (5, 7)]

最终索引应仅包含星期五(day_of_week = 4)小时 6 或星期六(day_of_week = 5)小时 7 的日期时间。

假设输入数据框如下:

2016-04-02 06:30:00  1
2016-04-02 06:45:00  2
2016-04-02 07:00:00  3
2016-04-02 07:15:00  4
2016-04-03 07:30:00  5
2016-04-03 07:45:00  6
2016-04-03 08:00:00  7

过滤后应该是这样的:

2016-04-02 06:30:00  1
2016-04-02 06:45:00  2
2016-04-03 07:30:00  5

因为我只保留列表中的星期几和一天中的小时的索引 [(4, 6), (5, 7)]

4

2 回答 2

6

您可以存储 in 变量中的dayofweekandhour方法index,然后将它们与iloc过滤器一起使用:

dayofweek = df.index.dayofweek
hour = df.index.hour

df.iloc[((dayofweek == 4) & (hour == 6)) | ((dayofweek == 5) & (hour == 7))]
于 2018-01-31T16:41:44.383 回答
4

您应该添加一个 columnday_of_week和一个 column hour,然后您可以在此列上归档。

例如 :

df["day_of_week"] = df["date"].dayofweek()
df["hour"] = df["date"].hour()

pd.concat([
    df.loc[df["day_of_week"].isin(x[0]) & df["hour"].isin(x[1])]
    for x in [(4, 6), (5, 7)]
])

请注意,我会遍历您的所有条件,然后连接所有生成的数据帧。

于 2018-01-31T16:23:27.013 回答