网站建设资讯详细

人工智能-Python中的pandas - groupby+agg聚合重命名解决办法

发表日期:2023-06-27 10:33:18   作者来源:水沐教育科技技术团队   浏览:2437       

在数据分析过程中,遇到需要对数据分组并展示成图的需要,在使用pandas中的groupby+agg聚合重命名时遇到如下问题:

return self._engine.get_oc(self._maybe_cast_indexer(key))File "pandas/_libs/index.pyx",line 108,in pandas._libs.index.IndexEngine.get_locFile "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_locFile "pandas/_libs/hashtable_class_helper.pxi", ine 1601, in pandas._libs.hashtable.Py0bjectHashTable.get_itemFile "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.Py0bjectHashTable.get_itemKeyError:,性别,

如下图所示:

解决方法如下:在grouped = data.groupby('性别).agg({'企微存量好友数': 'mean', '企微存量激活好友订单数': 'mean'}),这段中加个as_index=False

修改后的语句:grouped = data.groupby('性别',as_index=False).agg({'企微存量好友数': 'mean', '企微存量激活好友订单数': 'mean'}),

再次执行后,能正确展示出来了,如下:

注意点:

1数据格式参数说明:


1.1a s_index默认为True,即返回以组标签作为索引的对象。下例,Gender作为索引返回。
gender_df = df.groupby("Gender", as_index=True).agg({'CustomerID':'count'})
gender_df


1.2 as_index=False时,分组以列的方式返回,类SQL的分组。下例,Gender作为列名返回。
gender_df = df.groupby("Gender", as_index=False).agg({'CustomerID':'count'})
gender_df

2聚合重命名的几种方法:


2.1 rename,注意这里agg里是大括号{},如:
gender_df2 = df.groupby("Gender", as_index=False)
    .agg({'CustomerID':'count'})
    .rename(columns={'CustomerID': 'user_count'})

2.2 agg(’new列名‘=(’列名‘, ’统计方法‘)),注意是括号(),as_index须为True,即作为索引返回。如:
gender_df3 = df.groupby("Gender")
        .agg(user_count=('CustomerID','count'))
        
2.3 groupby(as_index=False)['列名']的方式,注意这种方式as_index须为False。如:
gender_df4 = df.groupby('Gender', as_index=False)['CustomerID']
        .agg({"user_count": "count"})