简体   繁体   中英

How to perform two aggregate operations in one column of same pandas dataframe?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM