0

I have an issue writing query to pandas. I have a dataframe: (item_name, order_id, quantity, item_price1).

The task is to get the quantity sold of most expensive product. When I write the query like this:

df.groupby('item_name')['item_price1','quantity'].agg(['max','count']) 

it works fine. But when I try to sort the result of the query to find the most expensive one using sort_values like this:

df.groupby('item_name')['item_price1','quantity'].agg(['max','count']).sort_values(by='max', ascending=False).head(10)

it ends with the error:

Key error 'max'

What will be the right thing to do?

7
  • Have you tried: stackoverflow.com/questions/53964251/… ? Commented Nov 23, 2019 at 17:03
  • Have you created a new df with a column called max? Can you confirm this? Commented Nov 23, 2019 at 17:09
  • No, I have not. "max" in this case is an aggregate function Commented Nov 23, 2019 at 17:13
  • 1
    Since you've got multiple columns with multiple aggregation operations then you're going to have a multi-level columns index... you need to be more specific as to which of the "max"s you want to sort on Commented Nov 23, 2019 at 17:13
  • 1
    So you probably want: .sort_values(by=('item_price1', 'max'), ascending=False) ? Commented Nov 23, 2019 at 17:15

1 Answer 1

0

Moving my comments to answer:

When you do something like:

agg = df.groupby('item_name')['item_price1','quantity'].agg(['max','count']) 

You end up building a multi-level column index, in this case (agg.columns), is:

MultiIndex([('item_price1',   'max'),
            ('item_price1', 'count'),
            (   'quantity',   'max'),
            (   'quantity', 'count')],
           )

To then use that for sorting, you need to use the specific level, eg:

agg.sort_values(by=('item_price1', 'max'), ascending=False)

On a side note - you're using .head(10) there to limit the total output after fully sorting the data, but it might be better to use .nlargest if your sample size is small compared to the population, eg:

agg.nlargest(10, ('item_price1', 'max'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.