SpecificationError:不支持嵌套重命名程序在字典上使用agg函数时出错

2024-05-20 01:52:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用agg函数,并在数据帧上使用参数作为字典。字典的代码是

aggregations = {
'Fare' : { # Work on the fare column
    'mean_Fare': 'mean',
    'median_Fare':'median',
    'max_Fare' : max,
    'min_Fare' : min
},
'Age' : { # Work on age column
    'median_Age' : 'median',
    'min_Age' : min,
    'max_Age' : max,
    'range_Age' : lambda x: max(x) - min(x) # calculate the age range per group
}

}

在我的数据框中有列作为Fare和Age,在定义了这个字典之后,我使用了下面的代码,这给了我一个错误

df.groupby(['Pclass']).agg(aggregations)

错误是

    ---------------------------------------------------------------------------
SpecificationError                        Traceback (most recent call last)
<ipython-input-44-28d5d263d58b> in <module>
----> 1 df.groupby(['Pclass']).agg(aggregations)

~\anaconda3\lib\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    926         func = _maybe_mangle_lambdas(func)
    927 
--> 928         result, how = self._aggregate(func, *args, **kwargs)
    929         if how is None:
    930             return result

~\anaconda3\lib\site-packages\pandas\core\base.py in _aggregate(self, arg, *args, **kwargs)
    340                     # {'ra' : { 'A' : 'mean' }}
    341                     if isinstance(v, dict):
--> 342                         raise SpecificationError("nested renamer is not supported")
    343                     elif isinstance(obj, ABCSeries):
    344                         raise SpecificationError("nested renamer is not supported")

SpecificationError: nested renamer is not supported

Tags: inage字典isminmeanmaxagg
1条回答
网友
1楼 · 发布于 2024-05-20 01:52:22

如错误所示,不支持嵌套重命名器。因此,您需要按如下方式删除它:

aggregations = {
    'Fare':{ # work on the "Fare" column
       'mean',  # get the mean fare
       'median', # get median fare
        max,
        np.min
    },
    'Age':{     # work on the "Age" column
        'median',   # Find the max, call the result "max_date"
         min,
         max,
         lambda x: max(x) - min(x)  # Calculate the age range per group
    }
}

相关问题 更多 >