简体   繁体   中英

Python Pandas - Calculate Min, Max, and Mean with a function

I'm trying to create a function called sales_recap to calculate the minimum, maximum, and average value of a sale.

def sales_recap(sales)

for example, if I have a dataframe as an input like this:

sales = pd.DataFrame({
    'Type':['Electronics', 'Electronics', 'Electronics', 'Home_Decor', 'Home_Decor', 'Kids', 'Kids, 'Kids],
    'Price':[100,100,70,60,80,50,50,50]})

And if I run the function

sales_recap(sales)

it should give a result like this

recap = pd.DataFrame({
    'Type':['Electronics', 'Home_Decor','Kids'],
    'Min_Price':[70,60,50],
    'Average':[90,70,50],
    'Max_Price':[100,80,50]
})

I'm new to python and I still don't have the ideas how to do this with a function so that I can use the function with another inputs. Thank You: :)

Use groupby_agg :

>>> sales.groupby('Type').agg(Min_Price=('Price', 'min'),
                              Average=('Price', 'mean'),
                              Max_Price=('Price', 'max')).reset_index()

          Type  Min_Price  Average  Max_Price
0  Electronics         70     90.0        100
1   Home_Decor         60     70.0         80
2         Kids         50     50.0         50

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