Given the following DataFrame
user_ID product_id amount
1 456 1
1 87 1
1 788 3
1 456 5
1 87 2
... ... ...
The first column is the ID of the customer, the second is the ID of the product he bought and the 'amount' express if the quantity of the product purchased on that given day (the date is also taken into consideration). a customer can buy many products each day as much as he wants to.
I want to calculate the total of times each product is bought by the customer, so I applied a groupby
df.groupby(['user_id','product_id'], sort=True).sum()
now I want to sort the sum of amount in each group. Any help?
Suppose
df
is:Then you can use,
groupby
andsum
as before, in addition you can sort values by two columns[user_ID, amount]
andascending=[True,False]
refers ascending order of user and for each user descending order of amount:Output:
You could also use
aggregate()
:Output: