Home > OS >  Dataframe to dictionary merging keys in python
Dataframe to dictionary merging keys in python

Time:12-12

I have a dataframe as you can see in below:

enter image description here

Some pro1s have different pro2s.

I want to convert this dataframe to dictionary as:

bundles = {
        "12345" : ["a1",'b1','c1','e1'],
        '56789' : ['a1'],
        '98765' : ['b1','d1']
     }

Thank you!

CodePudding user response:

bundles = df.groupby('pro1')['pro2'].apply(list).to_dict()

Output:

>>> bundles
{
    '12345': ['a1', 'b1', 'c1', 'e1'],
    '56789': ['a1'],
    '98765': ['b1', 'd1']
}

CodePudding user response:

You can groupby on pro1 and create a list from pro2, finally convert to a dictionary:

out = df.groupby('pro1')['pro2'].agg(list).to_dict()
  • Related