基于panda中的时间间隔删除行



我有一个带有日期时间戳的数据帧(每1分钟(。我想把两排的时间间隔增加到5分钟。基本上保留第0行、第5行、第10行等,并删除其余行。我该怎么做?

Date                       Value
17/08/2017  04:00:00       0
17/08/2017  04:01:00       1
17/08/2017  04:02:00       2
17/08/2017  04:03:00       3
17/08/2017  04:04:00       4
17/08/2017  04:05:00       5
17/08/2017  04:06:00       6
17/08/2017  04:07:00       7
17/08/2017  04:08:00       8
17/08/2017  04:09:00       9
17/08/2017  04:10:00       10

感谢

首先使用to_datetime()方法将日期列转换为日期时间dtype(如果它已经是日期时间,则忽略此步骤(:

df['Date']=pd.to_datetime(df['Date'])

最后,你可以通过布尔掩码做到这一点:

newdf=df[df['Date'].dt.minute%5==0]

现在,如果你打印newdf,你会得到你想要的输出:

Date                    Value
0   2017-08-17 04:00:00     0
5   2017-08-17 04:05:00     5
10  2017-08-17 04:10:00     10

如果需要,使用reset_index()方法:

newdf=newdf.reset_index(drop=True)

上述代码输出:

Date                    Value
0   2017-08-17 04:00:00     0
1   2017-08-17 04:05:00     5
2   2017-08-17 04:10:00     10

最新更新