如何按星期几和一天中的小时过滤 pandas DatetimeIndex

mot*_*m79 4 python filter pandas datetimeindex

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

[(4, 6), (5, 7)]
Run Code Online (Sandbox Code Playgroud)

最终索引应仅包含星期五(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
Run Code Online (Sandbox Code Playgroud)

经过过滤后,应该是这样的:

2016-04-02 06:30:00  1
2016-04-02 06:45:00  2
2016-04-03 07:30:00  5
Run Code Online (Sandbox Code Playgroud)

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

cma*_*her 9

您可以存储in 变量中的dayofweek和hour方法index,然后使用它们进行iloc过滤:

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

df.iloc[((dayofweek == 4) & (hour == 6)) | ((dayofweek == 5) & (hour == 7))]
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 5

您应该添加一列day_of_week和一列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)]
])
Run Code Online (Sandbox Code Playgroud)

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