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
652 views
in Technique[技术] by (71.8m points)

count - Duplicate rows in pandas DF

I have a DF in Pandas, which looks like:

Letters Numbers
A       1
A       3
A       2
A       1
B       1
B       2
B       3
C       2
C       2

I'm looking to count the number of similar rows and save the result in a third column. For example, the output I'm looking for:

Letters Numbers Events
A       1       2
A       2       1
A       3       1
B       1       1
B       2       1
B       3       1
C       2       2

An example of what I'm looking to do is here. The best idea I've come up with is to use count_values(), but I think this is just for one column. Another idea is to use duplicated(), anyway I don't want construct any for-loop. I'm pretty sure, that a Pythonic alternative to a for loop exists.

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 groupby these two columns and then calculate the sizes of the groups:

In [16]: df.groupby(['Letters', 'Numbers']).size()
Out[16]: 
Letters  Numbers
A        1          2
         2          1
         3          1
B        1          1
         2          1
         3          1
C        2          2
dtype: int64

To get a DataFrame like in your example output, you can reset the index with reset_index.


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

...