Home > Back-end >  Dataframe to dictionary with list of items
Dataframe to dictionary with list of items

Time:06-16

I have this Dataframe:

df = 
     key value
0    1   kpi1
1    1   kpi2
2    1   kpi3
3    2   kpi4
4    2   kpi5

And I am trying to create a dictionary where for the same key, there's a list of values, like this:

d = {'1': ['kpi1', 'kpi2', 'kpi3'], '2': ['kpi4', 'kpi5']}

I have tried to use df.apply but I couldn't find a solution. Do you have some idea?

CodePudding user response:

Try this:

df.groupby('key')['value'].apply(list).to_dict()

Result:

{1: ['kpi1', 'kpi2', 'kpi3'], 2: ['kpi4', 'kpi5']}

  • Related