0

I have a column in pandas data frame where I want to find out the min and max of a column in the same result. But the problem is I am getting only one aggregated value in return.

import pandas as pd
print(df)

col1 col2
5    9
6    6
3    4
4    3

df.agg({'col1':'sum','col1':'mean'})

The output of this aggregation is giving only mean :

col1    4.5
dtype: float64

However, the output which I need should have both sums and mean for col1 and I am only getting mean.

3
  • 1
    you mean df.col1.agg(['sum','mean']) ? Commented May 4, 2019 at 6:20
  • @anky_91: I think, I jumped into reply too quickly. But this syntax does not resolve my query. I need the sum and mean in two different columns and not in two different rows. I need the output similar to the way of an SQL. For e.g. in SQL syntax when i write this query: select max(col1), sum(col1) from df; I get two different columns in my output for max and sum, I want same here as well. Commented May 4, 2019 at 6:28
  • Okay check answer below Commented May 4, 2019 at 8:00

1 Answer 1

2

Try below code:

import pandas as pd
from io import StringIO
content= """col1 col2
            5    9
            6    6
            3    4
            4    3
            """
df=pd.read_csv(StringIO(content),sep='\s+')
df.agg({"col1":["sum","mean"],"col2":"std"})

if you want to apply multiple functions in one columns, you has to use list, otherwise, the later function to col1 will replace the former. if you want to apply mutliple functions for different columns, just use dict inside of the agg fucntions.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @Yong Wang. It's working as expected. I cannot thank you enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.