0

I have a dataframe with 4 columns . The dataframe looks like this:

      date  sell price      cost price            discount
2019-10-13    2000            2000               0
2019-10-21    3000            3000               0

I need to find the total sum and average of 2 columns cost price and sell price. The output should be like:

                total      avg           
sell price       5000      2500          
cost price       5000      2500   

How can I get this?

gsa
  • 784
  • 1
  • 8
  • 20
riz
  • 39
  • 5
  • try `df['sell price'].sum()` and `df['sell price'].mean()` – baccandr Oct 26 '19 at 12:34
  • 1
    Possible duplicate of [Pandas - possible to aggregate two columns using two different aggregations?](https://stackoverflow.com/questions/18837659/pandas-possible-to-aggregate-two-columns-using-two-different-aggregations) – jtweeder Oct 26 '19 at 15:09

3 Answers3

1

Use DataFrame.agg:

  new_df=df[['sell_price', 'cost_price']].agg(['sum','mean']).T.rename(columns={'sum':'total','mean':'Avg'})
print(new_df)

             total     Avg
sell_price  5000.0  2500.0
cost_price  5000.0  2500.0
ansev
  • 28,746
  • 5
  • 11
  • 29
0

Use of aggregate should do this.

df.aggregate({"cost_price":['sum','mean'],"sell_price":['sum','mean']})

[update] why it does not work? Any error to see? img

abdoulsn
  • 708
  • 1
  • 11
  • 28
0

Try this:

df[["sell price", "cost price"]].agg( ["sum", "mean"]).stack().unstack(0).rename(columns={"sum": "total", "mean": "avg"})

Output:

            total     avg
sell price  5000.0  2500.0
cost price  5000.0  2500.0

[Program finished]
Grzegorz Skibinski
  • 12,152
  • 2
  • 9
  • 32