1

I have a DataFrame as follows:

shop | item_price  | item_sold
A    |    123      |     1
B    |    921      |     2
A    |     28      |     4
...

I want to find the total revenue by each shop. In SQL it looks like this:

SELECT shop, SUM((item_price * item_sold)) as revenue
FROM table
GROUP BY shop

I want to do it in Python using Pandas. I tried:

revenue_by_shop = table.groupby("shop")[table["item_price"] * table["item_sold"]].sum()

But that does not seem like the right answer.

1
  • 1
    In Pandas, you need to calculate the revenue first, then sum it, so something like this should work : df.assign(revenue=df.item_price * df.item_sold).groupby("shop").revenue.sum()
    – sammywemmy
    Sep 18, 2020 at 6:44

2 Answers 2

3

You can multiple values to Series and pass to groupby Series table["shop"]:

df = ((table["item_price"] * table["item_sold"])
              .groupby(table["shop"])
              .sum()
              .reset_index(name='revenue'))

Or create new column by DataFrame.assign and pass colum name shop to groupby:

df = (table.assign(revenue = table["item_price"] * table["item_sold"])
           .groupby("shop", as_index=False)['revenue']
           .sum())
3

I will do it in this way to not overcomplicate it.

df['revenue'] = df['item_price'] * df['item_sold']
revenue_by_shop = df.groupby("shop")['revenue'].sum()

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.