Pandas:选择两个日期之间的DataFrame行(日期时间索引) [英] Pandas: Selecting DataFrame rows between two dates (Datetime Index)

查看:6344
本文介绍了Pandas:选择两个日期之间的DataFrame行(日期时间索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DatetimeIndex的Pandas DataFrame和一列 MSE Loss
索引的格式如下:

I have a Pandas DataFrame with a DatetimeIndex and one column MSE Loss the index is formatted as follows:

DatetimeIndex(['2015-07-16 07:14:41', '2015-07-16 07:14:48',
           '2015-07-16 07:14:54', '2015-07-16 07:15:01',
           '2015-07-16 07:15:07', '2015-07-16 07:15:14',...]

它包括几天。

我想在不明确实际时间间隔的情况下选择特定日期的所有行(所有时间)。
例如:之间2015-07-16 07: 00:00 2015-07-16 23:00:00

I want to select all the rows (all times) of a particular days without specifically knowing the actual time intervals. For example: Between 2015-07-16 07:00:00 and 2015-07-16 23:00:00

I尝试了这里概述的方法:这里

I tried the approach outlined here: here

但是 df [date_from:date_to]

输出:

KeyError: Timestamp('2015-07-16 07:00:00')

所以它想要精确的指数。此外,我没有日期列。只有带日期的索引。

So it wants exact indices. Furthermore, I don't have a datecolumn. Only an index with the dates.

通过提供日期选择一整天的最佳方法是什么 2015-07-16 然后如何在特定日期内选择特定的时间范围?

What is the best way to select a whole day by just providing a date 2015-07-16 and then how could I select a specific time range within a particular day?

推荐答案

选项1

示例df:

df
                      a
2015-07-16 07:14:41  12
2015-07-16 07:14:48  34
2015-07-16 07:14:54  65
2015-07-16 07:15:01  34
2015-07-16 07:15:07  23
2015-07-16 07:15:14   1

看起来你在没有 .loc 的情况下尝试这个(不会起作用)没有它):

It looks like you're trying this without .loc (won't work without it):

df.loc['2015-07-16 07:00:00':'2015-07-16 23:00:00']
                      a
2015-07-16 07:14:41  12
2015-07-16 07:14:48  34
2015-07-16 07:14:54  65
2015-07-16 07:15:01  34
2015-07-16 07:15:07  23
2015-07-16 07:15:14   1

选项2

您可以对索引使用布尔索引:

You can use boolean indexing on the index:

df[(df.index.get_level_values(0) >= '2015-07-16 07:00:00') & (df.index.get_level_values(0) <= '2015-07-16 23:00:00')]

这篇关于Pandas:选择两个日期之间的DataFrame行(日期时间索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆