1

I am trying to go through some data to find which category of products had the highest revenue.

I can get the actual total revenue of the category with the highest revenue by running:

max_revenue_by_cat = summer_transactions.groupby('item_category_id')['total_sales'].sum().max()

But how do I then get what category_id that max revenue belonged to? i.e. the category_id with the highest number of total_sales

mheavers
  • 29,530
  • 58
  • 194
  • 315

3 Answers3

2

Use set_index + sum(level=0) + sort_values + iloc to index the first item.

df

   item_category_id  total_sales
0                 1          100
1                 1           10
2                 0          200
3                 2           20
4                 1          300
5                 0          100
6                 1           30
7                 2          400

r = df.set_index('item_category_id')\
      .total_sales.sum(level=0)\
      .sort_values(ascending=False)\
      .iloc[[0]]

item_category_id
1    440
Name: total_sales, dtype: int64

If you want this as a mini-dataframe, call reset_index on the result -

r.reset_index()

   item_category_id  total_sales
0                 1          440

Details

df.set_index('item_category_id').total_sales.sum(level=0)

item_category_id
1    440
0    300
2    420
Name: total_sales, dtype: int64

Here, the category with the largest sum is 1. Usually, with a small number of groups, the sort_values call takes negligible time, so this should be pretty performant.

cs95
  • 379,657
  • 97
  • 704
  • 746
1

I think you need idxmax, but for return index add []:

summer_transactions = pd.DataFrame({'A':list('abcdef'),
                                    'total_sales':[5,3,6,9,2,4],
                                    'item_category_id':list('aaabbb')})


df = summer_transactions.groupby('item_category_id')['total_sales'].sum()

s = df.loc[[df.idxmax()]]
print (s)
item_category_id
b    15
Name: total_sales, dtype: int64


df = df.loc[[df.idxmax()]].reset_index(name='col')
print (df)
  item_category_id  col
0                b   15
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Yes. I agree, first part of answers is same. But OP need second part and it is diffetent, so I think it is OK. – jezrael Dec 18 '17 at 16:42
1

By using coldspeed's data :-)

(df.groupby('item_category_id').total_sales.sum()).loc[lambda x : x==x.max()]


Out[11]: 
item_category_id
1    440
Name: total_sales, dtype: int64
BENY
  • 317,841
  • 20
  • 164
  • 234