user15470345
user15470345

Reputation:

Python Pandas Groupby averages

IThis is what I currently have. I want to know what the mean is for the first time a player plays and what the mean is for the second time a player players.

Player Time
A 5
A 8
B 7
B 12

I would like to know what the player's average time is the first time and the average time the second time. So the first time average would be 6 and the second time average would be 10.

Upvotes: 1

Views: 70

Answers (1)

Cimbali
Cimbali

Reputation: 11415

With groupby + cumcount() we get the number of the row within each group, i.e. whether the time is for first, second, etc. per player:

>>> df.groupby('Player').cumcount()
0    0
1    1
2    0
3    1
dtype: int64

Reusing that in simple groupby.mean() we have the following solution:

>>> df['Time'].groupby(df.groupby('Player').cumcount()).mean()
0     6.0
1    10.0
Name: Time, dtype: float64

Upvotes: 2

Related Questions