Skip to content
Advertisement

Pandas find most bought item given ClientID ItemID ItemQuantity

Among the columns of my DataFrame I have ClientID CartID FoodID Quantity, I would like to find what is the food that the client has bought the most.

I tried this:

JavaScript

But got a completely wrong output:

JavaScript

EDIT: I also tried

JavaScript

but this results in a pair (ClientID, Quantity of the most bought food), I need (Client, FoodID)

Advertisement

Answer

JavaScript

First get a df with contains the total Quantity for each ClientID, FoodID combination. Then sort the df on ClientID, Quantity so that highest Quantity per client appears on the top and finally drop the duplicates per client which will drop all the clients records except the top which happens to be max quantity.

Test case:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement