简体   繁体   English

通过工作日的日期时间列对数据框进行分组

[英]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. 如果可以说星期一,星期二的第一天是MO还是01,我很灵活,只要可以看到星期一,星期二,星期三,星期四,星期五,星期六和星期天进行了哪些消费即可。

try using .dt.day_name() and groupby(),sum() 尝试使用.dt.day_name()和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: 您应该将“ Day”转换为datetime类型,然后可以提取星期几并汇总其余各列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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