如何按星期几和一天中的小时筛选 pandas DatetimeIndex [英] How to filter a pandas DatetimeIndex by day of week and hour in the day
问题描述
我有一个熊猫DatetimeIndex,我想按星期几和一天中的小时与列表匹配的标准来过滤索引.例如,我有一个元组列表,指示每个TimeStamp有效(星期几,小时,分钟):
I have a pandas DatetimeIndex and I would like to filter the index by the criterion that the day of the week and hour of the day matches a list. For example, I have of list of tuples indicating valid (day of week, hour, minute) for each TimeStamp:
[(4, 6), (5, 7)]
最终索引应仅包含星期五(day_of_week = 4)小时6或星期六(day_of_week = 5)小时7的日期时间.
The final index should only contain date times that are Friday(day_of_week = 4) hour 6 or Saturday(day_of_week = 5) hour 7.
让我们说输入数据帧就像:
Lets say the input data frame is like:
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
在过滤器之后,应该是这样的:
After the filter, it should be like:
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)]
Because I only keep indices whose day of week and hour of the day in the list [(4, 6), (5, 7)]
推荐答案
您应该添加一列 day_of_week
和一列 hour
,然后您可以在此列中添加文件.
You should add a column day_of_week
and a column hour
, then you can filer on this columns.
例如:
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)]
])
请注意,我会遍历您的所有条件,然后将所有结果数据框连接起来.
Note that I iterate over all your conditions, then I concatenate all the resulting dataframe.
这篇关于如何按星期几和一天中的小时筛选 pandas DatetimeIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!