3

I have a pandas DataFrame like so

week  player_a  player_b
 1      True      True
 1      True     False
 1     False     False
 2     False      True
 2     False     False
 2      True     False

and I would like to count the number of True and False for each player by week, but I cannot seem to finagle this into a convenient pandas groupby or pivot table operation. The desired result would look like:

week            True  False
      player
 1   player_a     2     1
     player_b     1     2
 2   player_a     1     2
     player_b     1     2

2 Answers 2

6

Use DataFrame.melt first and then count crosstab:

df1 = df.melt('week', var_name='player')

df = pd.crosstab([df1['week'], df1['player']], df1['value'])

Or use DataFrame.pivot_table:

df = df1.pivot_table(index=['week', 'player'], columns='value', fill_value=0, aggfunc='size')

Or aggregate counts by GroupBy.size and reshape by Series.unstack:

df = df1.groupby(['week', 'player', 'value']).size().unstack(fill_value=0)

print (df)
value          False  True 
week player                
1    player_a      1      2
     player_b      2      1
2    player_a      2      1
     player_b      2      1

And solution with DataFrame.stack, SeriesGroupBy.value_counts and unstack:

df = df.set_index('week').stack().groupby(level=[0,1]).value_counts().unstack(fill_value=0)
print (df)
               False  True 
week                       
1    player_a      1      2
     player_b      2      1
2    player_a      2      1
     player_b      2      1
Sign up to request clarification or add additional context in comments.

Comments

6

Use pandas pivot_table function and aggregate by size.

df = df.pivot_table(index=['week','player'], columns='value', aggfunc='size', fill_value=0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.