Reputation: 715
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 groupby
routines but cannot fathom it.
Upvotes: 1
Views: 283
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