Python 筛选dataframe日期列(从月初算起的X个月)
很难找到解决我问题的办法 我有一个df:Python 筛选dataframe日期列(从月初算起的X个月),python,pandas,dataframe,Python,Pandas,Dataframe,很难找到解决我问题的办法 我有一个df: df = pd.DataFrame({'col':np.random.randn(len(date_rng)),'created_at':pd.date_range('2020-01-01', '2020-12-31', freq='D')}) df 输出为: col created_at 0 1.764052 2020-01-01 1 0.400157 2020-01-02 2 0.978738
df = pd.DataFrame({'col':np.random.randn(len(date_rng)),'created_at':pd.date_range('2020-01-01', '2020-12-31', freq='D')})
df
输出为:
col created_at
0 1.764052 2020-01-01
1 0.400157 2020-01-02
2 0.978738 2020-01-03
3 2.240893 2020-01-04
4 1.867558 2020-01-05
... ... ...
361 0.003771 2020-12-27
362 0.931848 2020-12-28
363 0.339965 2020-12-29
364 -0.015682 2020-12-30
365 0.160928 2020-12-31
所以问题是,我想过滤数据帧,以显示从最后6个月到本月第一个月的数据。例如,如果今天(2020年10月23日),我希望dataframe从4月1日开始显示结果
在11月,第一个日期结果应为5月1日,无论11月的日期如何
你知道怎么做吗
这应该是自动运行的,所以类似于:
df = df[(df.created_at.dt.month >= datetime.datetime.utcnow().month)
& (df.created_at.dt.year==datetime.datetime.utcnow().year)]
行不通
谢谢 您可以使用between来指定两个值之间的条件:
today = datetime.today()
target = today - timedelta(days=180)
df = df[lambda x: x['created_at'].between(datetime(target.year,target.month,1),today)]