You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas链式操作的函数中重命名分组聚合后的列?

Pandas分组聚合链式重命名列报错解决

先给出基础数据与原分组聚合函数:

import pandas as pd

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
                              'Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 24., 26.]})

# 原分组聚合函数
def summary_df_grpby(df_):
    return df_.groupby(["Animal"]).agg({"Max Speed": ["max", "min"]})

原手动修改列名的方式可行:

cols = ["animal_max_speed","animal_min_speed"]
grpd = summary_df_grpby(df)
grpd.columns = cols

但尝试将重命名逻辑整合到链式操作时,出现TypeError: 'list' object is not callable错误:

# 错误写法
def summary_df_grpby(df_):
    cols = ["animal_max_speed","animal_min_speed"]
    return df_.groupby(["Animal"]).agg({"Max Speed": ["max", "min"]}).rename(columns=cols)

错误原因

rename()方法的columns参数仅接受字典(列名映射关系)或可调用函数,直接传入列表会被Pandas当作可调用对象尝试执行,而列表不具备可调用性,因此触发报错。

三种可行解决方法

方法1:聚合时直接指定列名(推荐,更高效)

在agg中通过元组格式直接定义新列名,无需后续重命名操作:

def summary_df_grpby(df_):
    return df_.groupby(["Animal"]).agg(
        animal_max_speed=("Max Speed", "max"),
        animal_min_speed=("Max Speed", "min")
    )

方法2:构建字典映射实现rename

手动构建原多级列与新列名的映射关系,传入rename的columns参数:

def summary_df_grpby(df_):
    return df_.groupby(["Animal"]).agg({"Max Speed": ["max", "min"]}).rename(
        columns={
            ('Max Speed', 'max'): 'animal_max_speed',
            ('Max Speed', 'min'): 'animal_min_speed'
        }
    )

方法3:用set_axis直接替换列名

set_axis支持直接传入列名列表,适配链式操作场景:

def summary_df_grpby(df_):
    cols = ["animal_max_speed", "animal_min_speed"]
    return df_.groupby(["Animal"]).agg({"Max Speed": ["max", "min"]}).set_axis(cols, axis=1)

内容的提问来源于stack exchange,提问作者nipy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:48:20