简体   繁体   中英

Rename Pandas .agg() columns inside function call

Is there a way to do the following inside the .agg() function?

hl = df[["sym", "bid", "ask"]].groupby("sym").agg(["min", "max"])
hl = hl.rename(columns={"min": "low", "max": "high"})

I see from the pandas documentation that you can use pd.namedAgg to apply different aggregations to different columns but all I would like to do is rename the columns in the original .agg() call.

I am used to writing in a very terse language (kdb+/q) hence wanted to reduce the number of lines of code.

What about this?

import pandas as pd
from random import randint

# Create sample dataframe
df = pd.DataFrame([
    {'sym': randint(1, 10), 'bid': randint(1, 10), 'ask': randint(1, 10)} for _ in range(10)
     ]).sort_values('sym').reset_index(drop=True)

hl = df[["sym", "bid", "ask"]].groupby("sym").agg([('low', "min"), ('high', "max")])
Before agg. After agg.
输入数据框 输出数据框

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