Reputation: 304
I need to split the dataframe based on weekdays,
The actual dataframe looks like this,
df = pd.DataFrame({'values': [10,5,30,44,52,6,7,85,9,1,1,1,13,14,1,16]})
df['weekdays'] = ['Monday','Tuesday','Wednesay','Thursday','Friday','saturday','sunday',
'Tuesday','Wednesay','Thursday','Friday','saturday','sunday',
'Monday','Tuesday','Wednesday']
values weekdays
0 10 Monday
1 5 Tuesday
2 30 Wednesay
3 44 Thursday
4 52 Friday
5 6 saturday
6 7 sunday
7 85 Tuesday
8 9 Wednesay
9 1 Thursday
10 1 Friday
11 1 saturday
12 13 sunday
13 14 Monday
14 1 Tuesday
15 16 Wednesday
how to split the dataframe based on weekdays like shown below? I Tried splitting the dataframe as 7 rows each, but this adds data from consequtive week, so how not to add data from consequtive week and split the dataframe exactly like this below? Thanks in advance for help.
new_df_1
new_df_2
new_df_3
Upvotes: 1
Views: 180
Reputation: 71687
Create a grouper grp
using Series.shift
+ Series.eq
+ Series.cumsum
, then use this grouper to group the dataframe and use a dict comprehension to store each of grouped frame in dictionary:
grp = df['weekdays'].shift().eq('sunday').cumsum()
dfs = {f'df{k+1}': g for k, g in df.groupby(grp)}
Result:
print(dfs['df1'])
values weekdays
0 10 Monday
1 5 Tuesday
2 30 Wednesay
3 44 Thursday
4 52 Friday
5 6 saturday
6 7 sunday
print(dfs['df2'])
values weekdays
7 85 Tuesday
8 9 Wednesay
9 1 Thursday
10 1 Friday
11 1 saturday
12 13 sunday
print(dfs['df3'])
values weekdays
13 14 Monday
14 1 Tuesday
15 16 Wednesday
Upvotes: 3