简体   繁体   中英

pandas group by week & get last week data as new df

I have a df that has the following, df.dtypes :

key                 object
date                datetime64[ns]
username            object
answer              object
grade               object
dtype: object

I then group by week:

test_lastweek = df.groupby([pd.Grouper(key='date', freq='W-SAT')])['key'].count()

I can see that that are 45 records that fall with in the last week of 2019-08-17 :

date
2019-06-29     475
2019-07-06     294
2019-07-13    2311
2019-07-20     389
2019-07-27     554
2019-08-03     408
2019-08-10     587
2019-08-17      45
Freq: W-SAT, Name: key, dtype: int64

Question : How do I get the last weeks data, all 45 records with the data from df and make that into a new df?

you can just filter the dataframe using .loc if you want all records from last week

df_last_week = df.loc[df['date'] >= '2019-08-17']

let me know if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM