【问题标题】:Deleting rows based on time interval in pandas根据熊猫中的时间间隔删除行
【发布时间】:2021-07-31 22:12:07
【问题描述】:

我有一个带有日期时间时间戳的数据框(每 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

谢谢

【问题讨论】:

  • 如果你的数据以00:00开头,你可以试试df.iloc[::5]

标签: python pandas sorting datetime


【解决方案1】:

首先使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 2021-12-21
    • 2014-11-17
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2023-03-16
    相关资源
    最近更新 更多