Pandas DataFrame 按天/小时/分钟切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12910187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:26:59  来源:igfitidea点击:

Pandas DataFrame slicing by day/hour/minute

pythonpandasslice

提问by Vitali Molchan

I have pandas Dataframe with datetime index like 'YYYY-MM-DD HH:MM:SS'.

我有带有日期时间索引的Pandas数据框,如“YYYY-MM-DD HH:MM:SS”。

Index               Parameter
2007-05-02 14:14:08     134.8
2007-05-02 14:14:32     134.8 
2007-05-02 14:14:41     134.8 
2007-05-02 14:14:53     134.8 
2007-05-02 14:15:01     134.8 
2007-05-02 14:15:09     134.8 
......
2007-05-30 23:08:02     105.9 
2007-05-30 23:18:02     105.9 
2007-05-30 23:28:02     105.9 
2007-05-30 23:38:03     105.8 

It is possible to get slice a DataFrame by year df['2007']or by month df['2007-05']?

可以按年df['2007']或按月对 DataFrame 进行切片df['2007-05']吗?

But when I've tried to slice DataFrame by day, for example df['2007-05-02'], I've got the error:

但是,例如df['2007-05-02'],当我尝试按天对 DataFrame 进行切片时,出现错误:

KeyError: < Timestamp: 2007-02-05 00:00:00. 

I use the pandas version 8.0.1. Is it possible to slice DataFrame with smaller frequency than year or month? For example, by day or hour?

我使用Pandas版本 8.0.1。是否可以以比年或月更小的频率对 DataFrame 进行切片?例如,按天还是按小时?

回答by root

use df.ix[x:y]where xand yare datetime objects.

使用df.ix[x:y]wherexyare datetime 对象。

Example:

例子:

In [117]: frame.index.summary()
Out[117]: 'DatetimeIndex: 6312960 entries, 2000-04-05 00:01:00 to 2012-04-06 00:00:00\nFreq: T'


In [118]: x=datetime(2001, 4, 5, 0, 1)

In [119]: y=datetime(2001, 4, 5, 0, 5)

In [120]: print frame.ix[x:y]
                     radiation      tamb
2001-04-05 00:01:00  67.958873  8.077386
2001-04-05 00:02:00  50.801294  0.731453
2001-04-05 00:03:00  16.042035  6.944998
2001-04-05 00:04:00   5.678343  9.728967
2001-04-05 00:05:00  72.551601  7.652942

you can also do this:

你也可以这样做:

In [121]: print frame.ix[x]
radiation    67.958873
tamb          8.077386
Name: 2001-04-05 00:01:00