how to find the sum and average of multiple columns in pandas

## how to find the sum and average of multiple columns in pandas

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?

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
```

You may use the following syntax to get the average for each column and row in pandas DataFrame: (1) Average for each column: df.mean(axis=0) (2) Average for each row: df.mean(axis=1) Next, I’ll review an example with the steps to get the average for each column and row for a given DataFrame

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]
```

You may use the following syntax to sum each column and row in Pandas DataFrame: (1) Sum each column: df.sum(axis=0) (2) Sum each row: df.sum(axis=1) In the next section, you’ll see how to apply the above syntax using a simple example. Steps to Sum each Column and Row in Pandas DataFrame Step 1: Prepare your Data

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? Sum of more than two columns of a pandas dataframe in python Sum of all the score is computed using simple + operator and stored in the new column namely total_score as shown below 1 2

Pandas dataframe.sum () function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column.

Calculate sum across rows and columns in Pandas DataFrame Sum across rows and columns: import pandas as pd df = pd.DataFrame ([ [10, 20, 30, 40], [7, 14, 21, 28], [5, 5, 0, 0]],

Get mean (average) of rows and columns of DataFrame in Pandas Get mean (average) of rows and columns: import pandas as pd df = pd.DataFrame ([ [10, 20, 30, 40], [7, 14, 21, 28], [5, 5, 0, 0]],