Home > Net >  How to split a dataframe by week on a particular starting weekday (e.g, Thursday)?
How to split a dataframe by week on a particular starting weekday (e.g, Thursday)?

Time:03-29

I'm using Python, and I have a Dataframe in which all dates and weekdays are mentioned. And I want to divide them into Week (Like - Thursday to Thursday)

Dataframe - enter image description here

And Now I want to divide this dataframe in this format-

Date    Weekday
0   2021-01-07   Thursday
1   2021-01-08     Friday
2   2021-01-09   Saturday
3   2021-01-10     Sunday
4   2021-01-11     Monday
5   2021-01-12    Tuesday
6   2021-01-13  Wednesday
7   2021-01-14   Thursday,

Date    Weekday
0   2021-01-14   Thursday
1   2021-01-15     Friday
2   2021-01-16   Saturday
3  2021-01-17     Sunday
4  2021-01-18     Monday
5  2021-01-19    Tuesday
6  2021-01-20  Wednesday
7  2021-01-21   Thursday,

Date    Weekday
0  2021-01-21   Thursday
1  2021-01-22     Friday
2  2021-01-23   Saturday
3  2021-01-24     Sunday
4  2021-01-25     Monday
5  2021-01-26    Tuesday
6  2021-01-27  Wednesday
7  2021-01-28   Thursday,
Date    Weekday
0  2021-01-28   Thursday
1  2021-01-29     Friday
2  2021-01-30   Saturday.

In this Format but i don't know how can i divide this dataframe.

CodePudding user response:

You can use pandas.to_datetime if the Date is not yet datetime type, then use the dt.week accessor to groupby:

dfs = [g for _,g in df.groupby(pd.to_datetime(df['Date']).dt.week)]

Alternatively, if you have several years, use dt.to_period:

dfs = [g for _,g in df.groupby(pd.to_datetime(df['Date']).dt.to_period('W'))]

output:

[         Date   Weekday
 0  2021-01-07  Thursday
 1  2021-01-08    Friday
 2  2021-01-09  Saturday
 3  2021-01-10    Sunday,
           Date    Weekday
 4   2021-01-11     Monday
 5   2021-01-12    Tuesday
 6   2021-01-13  Wednesday
 7   2021-01-14   Thursday
 8   2021-01-14   Thursday
 9   2021-01-15     Friday
 10  2021-01-16   Saturday
 11  2021-01-17     Sunday,
           Date    Weekday
 12  2021-01-18     Monday
 13  2021-01-19    Tuesday
 14  2021-01-20  Wednesday
 15  2021-01-21   Thursday
 16  2021-01-21   Thursday
 17  2021-01-22     Friday
 18  2021-01-23   Saturday
 19  2021-01-24     Sunday,
           Date    Weekday
 20  2021-01-25     Monday
 21  2021-01-26    Tuesday
 22  2021-01-27  Wednesday
 23  2021-01-28   Thursday
 24  2021-01-28   Thursday
 25  2021-01-29     Friday
 26  2021-01-30   Saturday]
variants

As dictionary:

{k:g for k,g in df.groupby(pd.to_datetime(df['Date']).dt.to_period('W'))}

reset_index of subgroups:

[g.reset_index() for _,g in df.groupby(pd.to_datetime(df['Date']).dt.to_period('W'))]

weeks ending on Wednesday/starting on Thursday with anchor offsets:

[g.reset_index() for _,g in df.groupby(pd.to_datetime(df['Date']).dt.to_period('W-WED'))]
  • Related