如何按日期、类别按数据框分组并计算每个类别的项目数?
how to group by dataframe by date, by category and count the number of items per each category?
需要数据框按功能分组的帮助。
我需要按日期、按类别对初始数据框的数据进行分组,并计算每个类别的项目数
使用 [pd.Grouper(freq='M', key='check_date')]
叠加
结果数据框是应该创建的
初始数据帧
check_date category
1/20/2021 apple
1/19/2021 orrange
1/6/2021 orrange
1/6/2021 apple
2/11/2021 cherry
3/20/2021 apple
3/19/2021 apple
4/12/2021 Mango
4/15/2021 Mango
4/13/2021 Mango
5/28/2021 Mango
5/25/2021 orrange
结果数据框:
check_date apple orrange cherry
1/31/2021 2 2 0
2/28/2021 0 0 1
3/31/2021 2 0 0
4/30/2021 4 0 0
5/31/2021 0 1 0
你要做的是:
`df['Date'] = pd.to_datetime(df['check_date'])
df = df.drop(['check_date'], axis = 1)
df = df.pivot_table(index=['Date'], columns='category', aggfunc='size', fill_value=0)
df = df.groupby(pd.Grouper(freq='M')).sum()
print(df)
给出:
category Mango apple cherry orrange
Date
2021-01-31 0 2 0 2
2021-02-28 0 0 1 0
2021-03-31 0 2 0 0
2021-04-30 3 0 0 0
2021-05-31 1 0 0 1
需要数据框按功能分组的帮助。
我需要按日期、按类别对初始数据框的数据进行分组,并计算每个类别的项目数
使用 [pd.Grouper(freq='M', key='check_date')]
结果数据框是应该创建的
初始数据帧
check_date category
1/20/2021 apple
1/19/2021 orrange
1/6/2021 orrange
1/6/2021 apple
2/11/2021 cherry
3/20/2021 apple
3/19/2021 apple
4/12/2021 Mango
4/15/2021 Mango
4/13/2021 Mango
5/28/2021 Mango
5/25/2021 orrange
结果数据框:
check_date apple orrange cherry
1/31/2021 2 2 0
2/28/2021 0 0 1
3/31/2021 2 0 0
4/30/2021 4 0 0
5/31/2021 0 1 0
你要做的是:
`df['Date'] = pd.to_datetime(df['check_date'])
df = df.drop(['check_date'], axis = 1)
df = df.pivot_table(index=['Date'], columns='category', aggfunc='size', fill_value=0)
df = df.groupby(pd.Grouper(freq='M')).sum()
print(df)
给出:
category Mango apple cherry orrange
Date
2021-01-31 0 2 0 2
2021-02-28 0 0 1 0
2021-03-31 0 2 0 0
2021-04-30 3 0 0 0
2021-05-31 1 0 0 1