Pandas DataFrame计算重复行并填充列

时间:2017-03-25 10:38:36

标签: python pandas dataframe duplicates

我创建了一个DataFrame,现在需要计算每个重复行(例如df [' Gender']。假设性别'男性出现两次,女性出现三次,我需要这个专栏:

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

Pandas有办法做到这一点吗?

1 个答案:

答案 0 :(得分:7)

Gender

分组后使用cumcount方法
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

计数从0开始,所以我在那里添加了+ 1