pandas.core.base.SpecificationError: nested renamer is not supported

今天跟着老师写爬虫的时候发现报了个错,但是发现代码也没错,搞了半天之后发现是版本的原因

Traceback (most recent call last):
File “E:/code/python/PyCharm/bigdata/class/20201006/爬取豆瓣小说.py”, line 76, in
df_gp = df.groupby(by=[‘等级’])[‘star’].agg({‘人数’: np.size, ‘平均值’: np.mean, ‘最高分’: np.max, ‘最低分’: np.min})
File “E:\environment\Python\Python17-32\lib\site-packages\pandas\core\groupby\generic.py”, line 246, in aggregate
ret = self._aggregate_multiple_funcs(func)
File “E:\environment\Python\Python17-32\lib\site-packages\pandas\core\groupby\generic.py”, line 292, in _aggregate_multiple_funcs
raise SpecificationError(“nested renamer is not supported”)
pandas.core.base.SpecificationError: nested renamer is not supported

最后发现是pandas在 1.0版本后,更新了API写法——gropuby+agg分组+聚合函数的写法变了

首先,查看自己的pandas的版本,如果是1版本且报错如上,则课根据以下方法改

import pandas as pd
print (pd.__version__) # 我的是1.1.3

报错的代码片段

df_gp = df.groupby(by=['等级'])['star'].agg({
    
    '人数': np.size, '平均值': np.mean, '最高分': np.max, '最低分': np.min})

更改之后的代码片段

df_gp = df.groupby(by=['等级'])['star'].agg([('人数', np.size), ('平均值', np.mean), ('最高分', np.max), ('最低分', np.min)])

猜你喜欢

转载自blog.csdn.net/weixin_44635198/article/details/109184433
今日推荐