Question: I am learning about loops and I have this code to check if a number is prime or not, but doesn't work. Where is the bug?

```
x <- 7
y <- seq(1,sqrt(x),by=1)
for(i in 1: sqrt(x)){
 if(y[x%%y == 0]) {
   print("FALSE")
 }else{
   print("TRUE")
 }
}

```

This gives me the right solution, but it repeats the answer as many times as number of elements in i. Also I would like to ask how to use function inside a for with if: 

```
i <- c(1: sqrt(x))
y3 <- x%%i == 0
y4 <- y3[-1] 
for(value in i){
  if(y4 == FALSE) {
    print("TRUE")
  }else{
    print("FALSE")
  }
}

```

version 3, gives me the solution but for evey element in i:

```
x <- 107
i <- c(1: sqrt(x))
y3 <- c(x%%i == 0)
y4 <- y3[-1] 
for(value in i){
  if(all(y4==F)) {
    print("TRUE")
  }else{
    print("FALSE")
  }
}

```

Answer: 
We can `groupby` with `cumcount` and before that drop duplicates so each same, `user_id` and `sc_id` get the same `subcat_counter`. After that we `fillna` with `forwardfill (ffill)`:

```
df['subcat_counter'] = df.drop_duplicates(['user_id', 'sc_id'])\
                       .groupby(['user_id'])['sc_id']\
                       .cumcount()+1

df.fillna(method='ffill', inplace=True)

print(df)
   user_id  sc_id  subcat_counter
0        1    100             1.0
1        1    100             1.0
2        1    101             2.0
3        1    102             3.0
4        2    100             1.0
5        2    101             2.0
6        3    101             1.0
7        3    103             2.0

```
You can do it this way using `groupby`

```
df['subcat_counter'] = (df.groupby('user_id')['sc_id']
                          .transform(lambda x: x.diff().gt(0).cumsum() + 1))

```

Output:

```
   user_id  sc_id  subcat_counter
0        1    100               1
1        1    100               1
2        1    101               2
3        1    102               3
4        2    100               1
5        2    101               2
6        3    101               1
7        3    103               2

```