简体   繁体   中英

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 groupby routines but cannot fathom it.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM