我创建了一个DataFrame,现在需要计算每个重复行(例如df [' Gender']。假设性别'男性出现两次,女性出现三次,我需要这个专栏:
Gender Occurrence
Male 1
Male 2
Female 1
Female 2
Female 3
Pandas有办法做到这一点吗?
答案 0 :(得分:7)
按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
计数从0开始,所以我在那里添加了+ 1
。