How to find out for each product, how many were sold in Pandas DataFrame

Viewed 1283

I have a pandas dataframe like this:

      Name Product  Amount
0      Bob   Apple       1
1      Bob  Banana       2
2  Jessica  Orange       3
3  Jessica  Banana       4
4  Jessica  Tomato       3
5     Mary  Banana       2
6     John   Apple       3
7     John   Grape       1
import pandas as pd

data = [('Bob','Apple',1), ('Bob','Banana',2), ('Jessica','Orange',3),
      ('Jessica','Banana',4),('Jessica','Tomato',3), ('Mary','Banana',2),
      ('John','Apple',3),('John','Grape',1)]

df = pd.DataFrame(data,columns=['Name','Product','Amount'])

What I have done so far:

l = []
count=0
for i in range(0,8):
    row = df.iloc[i]
    
    if row.Product not in l:
        l.append(row.Product)

Now, l contains all the unique values in the Product column, but I need the total amount as well.

How can I find out for each product how many items were sold (for example, 4 units of Apple were sold)?

1 Answers

You're looking for .groupby() function:

print( df.groupby('Product')['Amount'].sum() )

Prints:

Product
Apple     4
Banana    8
Grape     1
Orange    3
Tomato    3
Name: Amount, dtype: int64

out = df.groupby('Product')['Amount'].sum()
print('{} units of Apple were sold.'.format(out.loc['Apple']))

Prints:

4 of Apple were sold.
Related