Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

pandas - How to assign count of unique values to the records in a data frame in python

I have a data frame like this:

IP_address
   IP1
   IP1
   IP1
   IP4
   IP4
   IP4
   IP4
   IP4
   IP7
   IP7
   IP7

I would like to take count of unique values in this column and add the count as a variable by itself. At the end, it should look like this:

IP_address  IP_address_Count
   IP1               3
   IP1               3
   IP1               3
   IP4               5
   IP4               5
   IP4               5
   IP4               5
   IP4               5
   IP7               3
   IP7               3
   IP7               3

I am able to take the unique values of the column using the below code:

unique_ip_address_count = (df_c_train.drop_duplicates().IP_address.value_counts()).to_dict()

However, I am not sure how to match these in a loop in python so that i can get the desired results in python. Any sort of help is much appreciated.

I am not able to find a equivalent answer in stackoverflow. If there is anything please direct me there. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use value_counts() with map

df['count'] = df['IP_address'].map(df['IP_address'].value_counts())


    IP_address  count
0   IP1         3
1   IP1         3
2   IP1         3
3   IP4         5
4   IP4         5
5   IP4         5
6   IP4         5
7   IP4         5
8   IP7         3
9   IP7         3
10  IP7         3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...