Search code examples
pythonpandasdataframedateweek-number

Get values with specific week number - Pandas


I have a df with a significant amount of values. I would like to select all values occured the last 5 weeks of my set. I have tried with timedelta. I am aware that my code is not running but it is just to give you an idea at what direction I am aiming. I also tried with nlargest but it only gives me 5 values of the prior week.

gdf_hpo['weeknumber']=gdf_hpo[DATE].dt.week
gdf_hpo_2 = gdf_hpo.copy(deep=True)

get_last_week=gdf_hpo_2['weeknumber'].max()
week_prior_5=gdf_hpo_2['weeknumber'].max() - timedelta(weeks=5)

Do you have an idea ? Thanks a lot


Solution

  • Just use slicing, should work. And as ijdnam_alim mentioned, use days.

    week_prior_5=gdf_hpo_2['weeknumber'].max() - timedelta(days=35)
    
    df_5weeks = gdf_hpo_2[(gdf_hpo_2.weeknumber <= gdf_hpo_2.weeknumber.max()) \
                           and (gdf_hpo_2.weeknumber > week_prior_5)]
    

    Let me know if this doesn't work.