I'm new to python and I'm trying to get accustomed to it.
Basically, I have an excel file with student info and I read it into python using pandas. It looks something like this:
_id | student_id | first_name | last_name | type | grade |
---|---|---|---|---|---|
1 | 1001 | John | Doe | Project | 5.92 |
2 | 1001 | John | Doe | Oral | 2.34 |
3 | 1001 | John | Doe | Quiz | 6.59 |
4 | 1001 | John | Doe | Essay | 9.58 |
5 | 1002 | Harry | Schmoe | Project | 8.92 |
6 | 1002 | Harry | Schmoe | Oral | 5.94 |
7 | 1002 | Harry | Schmoe | Quiz | 4.75 |
8 | 1002 | Harry | Schmoe | Essay | 9.58 |
I want to transform it into a dictionary to look like this:
[ {'_id': 1,'student_id': 1001,'first_name': 'John','last_name': 'Doe','results': [ {'type': 'Project', 'grade': 5.92} {'type': 'Oral', 'grade': 2.34} {'type': 'Quiz', 'grade': 6.59} {'type': 'Essay', 'grade': 9.58} ] }, {'_id': 2,'student_id': 1002,'first_name': 'Harry','last_name': 'Schmoe','results': [ {'type': 'Project', 'grade': 8.92} {'type': 'Oral', 'grade': 5.94} {'type': 'Quiz', 'grade': 4.75} {'type': 'Essay', 'grade': 9.58} ] }]
This is what I've tried, but it does not work as intended
grouped = df.groupby(['_id', 'student_id', 'first_name', 'last_name'])transformed_data = []for index, group in grouped: group_dict = {"_id": index[0],"student_id": index[1],"first_name": index[2],"last_name": index[3],"results": dict(zip(group['type'], group['grade'])) } transformed_data.append(group_dict)