How can I find mean for same value column? in pandas

Question:

I have dataframe, and I am trying to find mean of stars for each name

  Name  stars  
0   A      5
1   A      5
2   B      3
3   C      2
4   B      4
5   B      2
6   B      2

Output:
       count mean stars
    A   2     5.00
    C   1     2.00
    B   4     1.57
Asked By: Putthita Nuphasant

||

Answers:

Group the dataframe by Name, then apply len, and np.mean aggregates on stars column.

>>> df.groupby('Name')['stars'].agg(**{ 'count': len, 'mean stars': np.mean})

      count  mean stars
Name                   
A         2        5.00
B         4        2.75
C         1        2.00

Answered By: ThePyGuy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.