Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

python 3.x - Pandas groupby => AttributeError: 'function' object has no attribute 'mean'

I try to compute the average size of a population composed of men and women:

>>> import pandas as pd
>>> df = pd.DataFrame([[175 , 'male' ], [181 , 'male' ], [165 , 'female' ], [179 , 'male' ], [156 , 'female' ]], columns=['size', 'sex'])
>>> df.head()

    size    sex
0   175     male
1   181     male
2   165     female
3   179     male
4   156     female

I would like to use Pandas groupby method to compute the average. Therefore, the following command returns an error:

>>> df.groupby('sex').size.mean()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-a31e7f02b69d> in <module>()
----> 1 df.groupby('sex').size.mean()

AttributeError: 'function' object has no attribute 'mean'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.size is a DataFrameGroupBy function so that takes precedence with dot notation (.size). This is why the safer method to access columns is with brackets ['size']:

df.groupby('sex')['size'].mean()

sex
female    160.500000
male      178.333333
Name: size, dtype: float64

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...