pandas 过滤过去 x 天的熊猫数据框

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

filter pandas dataframe for past x days

pythondatetimepandas

提问by Josh

I have a dataframe with a date column that I update daily. I'd like to create a copy of it with just the past 30 day's of data.

我有一个包含我每天更新的日期列的数据框。我想用过去 30 天的数据创建它的副本。

I tried the following syntax based on what I know about doing this in R:

我根据我对在 R 中执行此操作的了解尝试了以下语法:

df[df[date]>dt.date.today()-30]

The date column is not the index but I'm not opposed to making it so if that helps!

日期列不是索引,但我不反对这样做,如果有帮助的话!

Thanks!

谢谢!

回答by TurtleIzzy

Try this:

尝试这个:

import datetime
import pandas as pd 


df[df.the_date_column > datetime.datetime.now() - pd.to_timedelta("30day")]

Update: Edited as suggested by Josh.

更新:按照 Josh 的建议进行编辑。

回答by piRSquared

consider the df

考虑 df

today = pd.datetime.today().date()
begin = today - pd.offsets.Day(90)
tidx = pd.date_range(begin, today)
df = pd.DataFrame(dict(A=np.arange(len(tidx))), tidx)

you can slice the last 30 days like this

你可以像这样切片过去 30 天

cut_off = today - pd.offsets.Day(29)
df[cut_off:]

             A
2016-09-23  61
2016-09-24  62
2016-09-25  63
2016-09-26  64
2016-09-27  65
2016-09-28  66
2016-09-29  67
2016-09-30  68
2016-10-01  69
2016-10-02  70
2016-10-03  71
2016-10-04  72
2016-10-05  73
2016-10-06  74
2016-10-07  75
2016-10-08  76
2016-10-09  77
2016-10-10  78
2016-10-11  79
2016-10-12  80
2016-10-13  81
2016-10-14  82
2016-10-15  83
2016-10-16  84
2016-10-17  85
2016-10-18  86
2016-10-19  87
2016-10-20  88
2016-10-21  89
2016-10-22  90