Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13951

How do I count unique values in the index of a pandas pivot_table?

$
0
0

Given a dataframe like this:

df = pd.DataFrame({'player': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],     'team': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C'],'game': [101, 102, 103, 101, 102, 104, 105, 101],'score': [10, 11, 12, 10, 11, 10, 12, 10]})

I can create a pivot_table that summarizes by player and team, with game as the column and summing the score:

pd.pivot_table(df, index = ['player', 'team'], columns = 'game', values = 'score', aggfunc = 'sum', fill_value = '')

This returns a table like this:

pivot_table output

What I want to do, though, is to count the number of unique teams each player played on, so that Abe, Brian and Claude all have 1, Henry has 2, and James has 3.

I've tried nunique and count_values but they seem only to work with numbers, not strings. I've seen questions that address the problem of counting unique values in the 'values' part of the pivot table, but not in the index part.


Viewing all articles
Browse latest Browse all 13951

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>