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

Viewed 196

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

```
2 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

It's not very clear whether your data is a dictionary where each item is a list:

{'Question': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5,etc...], 'Answer': [2, 2, 88, 4, 7, 2, 2, 85, 3, 7, 2, 2, 86, 4, 6,etc...], 'Student ID': []}

Or a list where each item is a dictionary:

[{'Question': 1, 'Answer': 2, 'Student ID': ''}, {'Question': 2, 'Answer': 2, 'Student ID': ''}, {'Question': 3, 'Answer': 88, 'Student ID': ''}, ...etc]

But here's a solution for both.

For the first situation you can loop through the questions with enumerate() to increment the index i and assign the Student ID with the integer division operator //:

for i, question in enumerate(data["Question"]):
    student_id = (i // 5) + 1
    data["Student ID"].append(student_id)
print(data)
    

Which gives (for example):

{'Question': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5], 'Answer': [2, 2, 88, 4, 7, 2, 2, 85, 3, 7, 2, 2, 86, 4, 6], 'Student ID': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]}

Or, for the second situation you can do:

for i, row in enumerate(data):
    student_id = (i // 5) + 1
    data[i]["Student ID"] = student_id
print(data)

Which gives:

[{'Question': 1, 'Answer': 2, 'Student ID': 1}, {'Question': 2, 'Answer': 2, 'Student ID': 1}, {'Question': 3, 'Answer': 88, 'Student ID': 1},etc..
Related