1

I have a data frame which contains several names who have bought and sold several products. I want to group them based on their names and calculate the total quantity, average buy price, sell price and profit.

  mydata:
          name,   quantity,   buy price,   sell price, profit
           A1,       10   ,      23    ,         25  ,     2
           A3,        8   ,      100   ,         32  ,   -68
           A1,        2   ,      3     ,          7  ,     4
           B1,       12   ,      13    ,         15  ,     2
           B1,        3   ,      10    ,          3  ,     -7 
           C1,        2   ,      3     ,          7  ,     4
           C1,        1   ,      4     ,          5  ,     1

So, my desired output should be like this:

  output:
           name  total(quantity)  average (buy price) average (sell price) average (profit)   
            A1          12                   20                   16                3
            A3          8                   100                   32               -68
            B1          15                  11.5                   9               -3.5
            C1          3                   3.5                    6                 3
Tom Klarin
  • 33
  • 8

1 Answers1

0

Let's say you put your dataframe in a pandas DataFrame called df, then you can do:

df.groupby('name')['quantity'].sum()

output:

name
A1    12
A3     8
B1    15
C1     3
Name: quantity, dtype: int64

and,

df.groupby('name')['sell price'].mean()

output:

name
A1    16
A3    32
B1     9
C1     6
Name: sell price, dtype: int64
myradio
  • 1,703
  • 1
  • 15
  • 25