Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning +1 values (incremental) for every 5 rows in Python

I have 1000 rows of answers that belong to 200 students for 5 questions. I do not have student ID data so I would like to assign them manually.

Question  Answer Student ID
1           2        1
2           2        1
3           88       1
4           4        1
5           7        1
1           2        2
2           2        2
3           85       2
4           3        2
5           7        2
.           .        .
.           .        .
.           .        .

I would like to automatically assign incremental values for every 5 rows for Student ID column.

I am trying this loop where if the value of 5 rows before the current row is the same as the value trying to assign, do +1 and continue to the end. But it is yielding error. What can I do to fix so I can yield student ID for every 5 questions?

I would greatly appreciate your help.


i = 1
data['Student_ID'] = 1
for i, row in data.iterrows():
    if row['Student ID'].shift(-4) == i:
        row['Student ID'] += i 
    else:
        row['Student ID'] == i

```
like image 764
1 isak Avatar asked Aug 10 '26 07:08

1 isak


1 Answers

Use integer division by 5:

df['Student ID'] = df.index // 5 + 1
print (df)
   Question  Answer  Student ID
0         1       2           1
1         2       2           1
2         3      88           1
3         4       4           1
4         5       7           1
5         1       2           2
6         2       2           2
7         3      85           2
8         4       3           2
9         5       7           2

If not default index values:

df['Student ID'] = np.arange(len(df)) // 5 + 1
like image 88
jezrael Avatar answered Aug 11 '26 20:08

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!