pandas将dataframe与具有最大和值的类别列分组

pandas将dataframe与具有最大和值的类别列分组,pandas,pandas-groupby,Pandas,Pandas Groupby,我想用列对数据帧进行分组 datetime index category product_name sale_price. 我需要将它分组,以便 year_month sum_of_sale_price_for_year_month product_name_max_contributed_price_year_month 如果数据帧具有如下值: | datetime | category | product_name | sale_price| |

我想用列对数据帧进行分组

datetime index
category
product_name
sale_price.
我需要将它分组,以便

year_month
sum_of_sale_price_for_year_month
product_name_max_contributed_price_year_month
如果数据帧具有如下值:


| datetime  |  category  |  product_name  | sale_price|
|                                                     |
|2012-07-04 | category_1 |  product_1     | 120       |
|2012-07-07 | category_1 |  product_2     | 270       |
|2012-07-09 | category_1 |  product_7     | 100       |
|2012-07-12 | category_1 |  product_5     | 315       |

输出应该是

| year_month | product_name_max_contributed_price_year_month | sum_of_sale_price_for_year_month|
|                                                                                              |
|  2012-07   |  product_5                                    |  805                            |
列名可以是任何名称,这只是为了理解。 我已经能够应用以下过程:

grouped_df = df.groupby([(df.index.year.rename('year')),(df.index.month.rename('month'))]).agg({"sale_price:np.sum"})
grouped_df['year_month'] = grouped_df [['year','month']].apply(lambda x: datetime.strptime('{}-{}'.format(x[1],x[0]), '%m-%Y').strftime('%b-%y'), axis=1)
我需要一个额外的列,该列提供产品名称,其中包含时间范围内的最大贡献。 它要么我搜索每个产品名称,对应于分组的年和月的最大值,创建一个系列并附加到它。 最好的方法是什么?

创建数据帧

import pandas as pd

df = pd.DataFrame({'datetime': ['2012-07-04', '2012-07-07', '2012-07-09 ', '2012-07-12'], 
                   'category': ['category1', 'category1', 'category1', 'category1'],
                   'product_name': ['product_1','product_2','product_7','product_5'],
                   'sale_price': [120,270,100,315]})
创建年-月列:

df['year_month'] = pd.to_datetime(df['datetime']).dt.to_period('M')
查找当月销售额:

s = df.groupby(['year_month'])['sale_price'].sum().to_frame().rename(columns={"sale_price": "sum_of_sale_price_year_month"}).reset_index()
寻找销售金额最大的产品。idxmax是关键函数。它返回请求的groupby轴上第一次出现的最大销售价格的索引,并将其放入loc函数中,该函数将拉出与该索引关联的整行。然后从此行中提取年份\月份和产品\名称,其中一个名称被重命名,索引被重置,以便在下一步进行联接

grouped_df = df.loc[df.groupby(['year_month'])['sale_price'].idxmax()][['year_month','product_name']].rename(columns={"product_name": "product_name_max_contributed_price_year_month"}).reset_index(drop=True)
合并年-月字段:

df2 = pd.merge(s, grouped_df, on='year_month')
      year_month    sum_of_sale_price_year_month product_name_max_contributed_price_year_month
    0 2012-07       805                          product_5