I want to group pandas dataframe with columns
datetime index
category
product_name
sale_price.
I need to group it in such a way that i have
year_month
sum_of_sale_price_for_year_month
product_name_max_contributed_price_year_month
if a data frame has values like
| 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 |
The output should be
| year_month | product_name_max_contributed_price_year_month | sum_of_sale_price_for_year_month|
| |
| 2012-07 | product_5 | 805 |
The column names can be anything, its just for understanding. I have been able to apply following process :
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)
i need additional column that gives product_name with max contribution for the time range. its either i search for each product_name corresponding to max value for year and month in grouped_df and create a series and append to it. what is the best way ?