1

[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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
luci
  • 13
  • 3
  • Bugs in this code aside, I'm murderously sure we could come up with a better pandas-native solution if you shared a sample dataframe and the desired result. – timgeb Dec 16 '21 at 10:10
  • ID:1,1,1,2,2,3,3,4,4,4,5,6 and count must be count:1,2,3,1,2,1,2,1,2,3,1,1 – luci Dec 16 '21 at 10:11
  • ID:1,1,1,2,2,3,3,4,4,4,5,6 and count must be count:1,2,3,1,2,1,2,1,2,3,1,1 – luci Dec 16 '21 at 10:15

1 Answers1

0

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
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Thank you very much! Is there any way to do the same with while loop? Now I am studying while loop and want to use it instead – luci Dec 16 '21 at 10:20
  • @luci yes of course. But I won't write the code for you ;) – timgeb Dec 16 '21 at 10:21
  • :) I know I must add something in while otherwise the loop never stops. I don't want the whole code just some hint what's wrong with my code and how to fix it – luci Dec 16 '21 at 10:26