DGraham
DGraham

Reputation: 715

count of unique occurrences of a value pandas python

So I have an extremely simple dataframe:

values
1
1
1
2
2

I want to add a new column and for each row assign the sum of it's unique occurences, so the table would look like:

values unique_sum
1 3
1 3
1 3
2 2
2 2

I have seen some examples in R, but for python and pandas I have not come across anything and am stuck. I can list the value counts using .value_counts() and I have tried groupbyroutines but cannot fathom it.

Upvotes: 1

Views: 283

Answers (1)

BrenBarn
BrenBarn

Reputation: 251365

Just use map to map your column onto its value_counts:

>>> x
   A
0  1
1  1
2  1
3  2
4  2
>>> x['unique'] = x.A.map(x.A.value_counts())
>>> x
   A  unique
0  1       3
1  1       3
2  1       3
3  2       2
4  2       2

(I named the column A instead of values. values is not a great choice for a column name, because DataFrames have a special attribute called values, which prevents you from getting the column with x.values --- you'd have to use x['values'] instead.)

Upvotes: 2

Related Questions