python - How to count the number of group elements with pandas -


i have dataframe , want count number of elements in each group. know, can use groupby().count() counts of columns, me, want number of elements in each group. how can this?

here example:

mydf = pd.dataframe({"fruit":["apple","banana","apple"],"weight":[7,8,3],"price":[4,5,6]}) mydf >>     fruit  price  weight >> 0   apple      4       7 >> 1  banana      5       8 >> 2   apple      6       3 

if use groupby("fruit").mean(), value each column.

mydf.groupby("fruit").mean()  >>         price  weight >> fruit                 >> apple       2       2 >> banana      1       1 

but expect output is:

>>         number_of_fruit >> fruit                 >> apple       2   >> banana      1 

how can this?

you want size count number of each fruit:

in [102]: mydf.groupby('fruit').size()  out[102]: fruit apple     2 banana    1 dtype: int64 

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -