Pandas DataFrame count duplicate rows and fill in column

百般思念 提交于 2019-12-23 13:23:12

问题


I have created a DataFrame, and now need to count each duplicate row (by for example df['Gender']. Suppose Gender 'Male' occurs twice and Female three times, I need this column to be made:

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

Is there a way to do this with Pandas?


回答1:


Use the cumcount method after grouping by 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 with 0 so I added a + 1 there.



来源:https://stackoverflow.com/questions/43015345/pandas-dataframe-count-duplicate-rows-and-fill-in-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!