0

this is the data frame:

     course_id  weight
0          1      10
1          1      40
2          1      50
3          2      40
4          2      60
5          3      90
6          3      10

want to convert it to a dictionary like:

{1 : [10,40,50] , 2:[40,60] , 3 :[90,10]}
df = pd.read_csv(tests) 
df = df[['course_id','weight']]
print(df)

   
azro
  • 53,056
  • 7
  • 34
  • 70
Manasa
  • 11
  • 7

1 Answers1

0

You need to groupby course_id column, then keep weight, put values in lists, and use to_dict() to get final structure

import pandas as pd

df = pd.DataFrame({'course_id': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3},
                   'weight': {0: 10, 1: 40, 2: 50, 3: 40, 4: 60, 5: 90, 6: 10}})
result = df.groupby("course_id")['weight'].apply(list).to_dict()
print(result)  # {1: [10, 40, 50], 2: [40, 60], 3: [90, 10]}
azro
  • 53,056
  • 7
  • 34
  • 70