0

I would like to get a new column of Occurance like df2. Thanks

import pandas as pd
import sys
import numpy as np
df=pd.DataFrame({'A':['1','2','1','3','4','2','1']})
print(df)

#my ideal case
df2=pd.DataFrame({'A':['1','2','1','3','4','2','1'],'Occurance':['1','1','2','1','1','2','3']})
print(df2)
datou
  • 1

1 Answers1

0

Try groupby function with cumcount:

df["Occurence"] = df.groupby("A").cumcount() + 1  # +1 since cumcount starts at 0

Output:

    A   Occurence
0   1   1
1   2   1
2   1   2
3   3   1
4   4   1
5   2   2
6   1   3
rftr
  • 1,185
  • 2
  • 10
  • 19