Skip to content Skip to sidebar Skip to footer

Count Of Unique Values Per Group As New Column With Pandas

I would like to count the unique observations by a group in a pandas dataframe and create a new column that has the unique count. Importantly, I would not like to reduce the rows i

Solution 1:

GroupBy.transform('nunique')

On v0.23.4, your solution works for me.

df['ncount'] = df.groupby('mID')['uID'].transform('nunique')
df
      uID mID  ncount
0   James   A       5
1   Henry   B       2
2     Abe   A       5
3   James   B       2
4   Henry   A       5
5   Brian   A       5
6  Claude   A       5
7   James   C       1

GroupBy.nunique + pd.Series.map

Additionally, with your existing solution, you could map the series back to mID:

df['ncount'] = df.mID.map(df.groupby('mID')['uID'].nunique())
df
      uID mID  ncount
0   James   A       5
1   Henry   B       2
2     Abe   A       5
3   James   B       2
4   Henry   A       5
5   Brian   A       5
6  Claude   A       5
7   James   C       1

Solution 2:

You are very close!

df['ncount'] = df.groupby('mID')['uID'].transform(pd.Series.nunique)

      uID mID  ncount
0   James   A       5
1   Henry   B       2
2     Abe   A       5
3   James   B       2
4   Henry   A       5
5   Brian   A       5
6  Claude   A       5
7   James   C       1

Post a Comment for "Count Of Unique Values Per Group As New Column With Pandas"