Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...