简体   繁体   中英

Group Dataframe with datetime column by weekday

I have a dataframe with one column in datetime format and the other columns in integers and floats. I would like to group the dataframe by the weekday of the first column. The other columns would be added.

print (df)
Day               Butter Bread Coffee
2019-07-01 00:00:00 2   2   4
2019-07-01 00:00:00 1  2   1
2019-07-02 00:00:00 5  4   8

Basically the outcome would be sometime alike:

print (df)
Day Butter Bread Coffee
Monday 3   4   5
Tuesday 5  4   8

I am flexible if it says exactly Monday, or MO or 01 for the first day of the week, as long it is visible which consumption was done on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.

try using .dt.day_name() and groupby(),sum()

df = pd.DataFrame(data={'day':['2019-07-01 00:00:00','2019-07-01 00:00:00','2019-07-02 00:00:00'],
                       'butter':[2,1,5],
                       'bread':[2,2,4],
                       'coffee':[4,1,8]}) 
df['day'] = pd.to_datetime(df['day']).dt.day_name()
df.groupby(['day'],as_index=False).sum()

     day    butter  bread   coffee
0   Monday      3      4    5
1   Tuesday     5      4    8

You should convert your "Day" to datetime type and then you can extract the day of the week and aggregate over the rest of the columns:

import pandas as pd
df['Day'] = pd.to_datetime(df['Day'])
df.groupby(df['Day'].dt.day_name()).sum()

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