如何根据日期时间索引对 Pandas Dataframe 进行切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49868647/
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-14 05:28:36  来源:igfitidea点击:

How to slice a Pandas Dataframe based on datetime index

pythonpandasslice

提问by 0000

This has been bothering me for ages now:

这一直困扰着我多年:

Given a simple pandas DataFrame

给定一个简单的 Pandas DataFrame

>>> df

Timestamp     Col1
2008-08-01    0.001373
2008-09-01    0.040192
2008-10-01    0.027794
2008-11-01    0.012590
2008-12-01    0.026394
2009-01-01    0.008564
2009-02-01    0.007714
2009-03-01   -0.019727
2009-04-01    0.008888
2009-05-01    0.039801
2009-06-01    0.010042
2009-07-01    0.020971
2009-08-01    0.011926
2009-09-01    0.024998
2009-10-01    0.005213
2009-11-01    0.016804
2009-12-01    0.020724
2010-01-01    0.006322
2010-02-01    0.008971
2010-03-01    0.003911
2010-04-01    0.013928
2010-05-01    0.004640
2010-06-01    0.000744
2010-07-01    0.004697
2010-08-01    0.002553
2010-09-01    0.002770
2010-10-01    0.002834
2010-11-01    0.002157
2010-12-01    0.001034

How do I separate it so that a new DataFrame equals the entries in df for the dates between 2009-05-01and 2010-03-01

我如何将它分开,以便新的 DataFrame 等于 df2009-05-01和之间日期的条目2010-03-01

>>> df2

Timestamp     Col1
2009-05-01    0.039801
2009-06-01    0.010042
2009-07-01    0.020971
2009-08-01    0.011926
2009-09-01    0.024998
2009-10-01    0.005213
2009-11-01    0.016804
2009-12-01    0.020724
2010-01-01    0.006322
2010-02-01    0.008971
2010-03-01    0.003911

回答by user1319128

If you have set the "Timestamp" column as the index , then you can simply use

如果您已将“时间戳”列设置为索引,那么您只需使用

df['2009-05-01' :'2010-03-01']

回答by rafaelc

IIUC, a simple slicing?

IIUC,一个简单的切片?

from datetime import datetime
df2 = df[(df.Timestamp >= datetime(2009, 05, 01)) &
         (df.Timestamp <= datetime(2010, 03, 01))]

回答by Kunal Vats

You can do something like:

您可以执行以下操作:

df2 = df.set_index('Timestamp')['2009-05-01' :'2010-03-01']
print(df2)