Pandas DataFrame counts duplicate rows and populates a column

I created a DataFrame, and now you need to count every repeated row (for example, df ['Gender']. Suppose that the gender “Male” occurs twice, and the woman three times, I need this column:

Gender   Occurrence
Male     1
Male     2
Female   1
Female   2
Female   3

Is there any way to do this with Pandas?

+4
source share
1 answer

Use the cumcount method after grouping Gender:

df = pd.DataFrame({'Gender':['Male','Male','Female','Female','Female']})   
df['Occurrence'] = df.groupby('Gender').cumcount() + 1
print(df)

   Gender  Occurrence
0    Male           1
1    Male           2
2  Female           1
3  Female           2
4  Female           3

Counts start at 0, so I added there + 1.

+7
source

Source: https://habr.com/ru/post/1673184/


All Articles