Home > Software design >  Make a list inside the dictionary in python
Make a list inside the dictionary in python

Time:01-06

I have a data frame like below. I want to get a dictionary consisting of a list.My expected output is. Can you pls assist me to get it? enter image description here

enter image description here

CodePudding user response:

You can use the handy groupby function in Pandas:

df = pd.DataFrame({
    'Department': ['y1', 'y1', 'y1', 'y2', 'y2', 'y2'], 
    'Section': ['A', 'B', 'C', 'A', 'B', 'C'], 
    'Cost': [10, 20, 30, 40, 50, 60]
})

output = {dept: group['Cost'].tolist() for dept, group in df.groupby('Department')}

gives

{'y1': [10, 20, 30], 'y2': [40, 50, 60]}
  •  Tags:  
  • Related