[enter image description here][I have ID column and want to add count for ids like in count column in pd dataframe. I want to do that using while loop. I tried this but I am getting never ending loop.
ID:1,1,1,2,2,3,3,3,4,5,6
count must be
COUNT:1,2,3,1,2,1,2,3,1,1,1
i=1
sum=1
n=len(df)
while i < n:
if df.loc[i,"ID]=df.loc[i-1,"ID"]:
sum+=1
df.loc[i,"Count"]=sum
i+=1
else:
i=1
Please help!
>Solution :
groupby, then transform with 'cumcount'.
>>> df = pd.DataFrame({'ID': [1,1,1,2,2,3,3,4,4,4,5,6]})
>>> df
ID
0 1
1 1
2 1
3 2
4 2
5 3
6 3
7 4
8 4
9 4
10 5
11 6
>>> df['count'] = df.groupby('ID').transform('cumcount') + 1
>>> df
ID count
0 1 1
1 1 2
2 1 3
3 2 1
4 2 2
5 3 1
6 3 2
7 4 1
8 4 2
9 4 3
10 5 1
11 6 1