按日期/小时/分钟对Pandas DataFrame进行切片 [英] Pandas DataFrame slicing by day/hour/minute
本文介绍了按日期/小时/分钟对Pandas DataFrame进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有日期时间索引为"YYYY-MM-DD HH:MM:SS"的熊猫数据框.
I have pandas Dataframe with datetime index like '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
是否可以按年份df['2007']
或按月份df['2007-05']
分割DataFrame?
It is possible to get slice a DataFrame by year df['2007']
or by month df['2007-05']
?
但是当我尝试按天对DataFrame进行切片时,例如df['2007-05-02']
,我得到了错误:
But when I've tried to slice DataFrame by day, for example df['2007-05-02']
, I've got the error:
KeyError: < Timestamp: 2007-02-05 00:00:00.
我使用的是熊猫8.0.1版.是否可以以比年或月小的频率对DataFrame进行切片?例如,按天还是按小时?
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?
推荐答案
使用df.ix[x:y]
,其中x
和y
是日期时间对象.
use df.ix[x:y]
where x
and y
are datetime objects.
示例:
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
您也可以这样做:
In [121]: print frame.ix[x]
radiation 67.958873
tamb 8.077386
Name: 2001-04-05 00:01:00
这篇关于按日期/小时/分钟对Pandas DataFrame进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文