Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to restart loop in pandas using while

[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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading