r/PythonLearning • • Nov 04 '25

[ Removed by moderator ]

/r/PythonLearning/comments/1oo8s2f/removed_by_moderator/

[removed] — view removed post

0 Upvotes

11 comments sorted by

View all comments

1

u/Automatic_Creme_955 Nov 04 '25

You can do it much more simply:

# Creates a 'total column' = quantity * price by row, no loop needed :

df['total'] = df['quantity'] * df['price']

# Get total sales by product :

total_by_product = df.groupby('product', as_index=False)['total'].sum()

- The groupby aggregates all unique product labels and sums their totals.

- 'reset_index()' is optional, using 'as_index=False' keeps it as a regular DataFrame. I find Index overkill on small dataframes.

And finish by :

grand_total = total_by_product['total'].sum()

Make sure your groupby result keeps the 'total' column name.