leoOrion
leoOrion

Reputation: 1957

Convert pandas df to a dict of key column to array of rows

I have a df like this -

     article_id brand                 brand_name category category_name   id           
0         200421   751                 milky mist     1402   perishables  1721     
1         202860   364                   epigamia     1402   perishables  1718     
2         203777   364                   epigamia     1402   perishables  1718     
0         200422   751                 milky mist     1402   perishables  1721     

I want to convert this to a dict where the keys are the id col values and each of them maps to an array of dicts which are the rows that have the id value -

{
    "1721": [{
        "article_id": 200421,
        ...# remaining fields
    },
    {
        "article_id": 200422,
        ...
    }],
    "1718": 
        ... All the rows that have this id in dict form.
    ]

}

I have tried setting the index to the id column and converting to a dict based on orient index, but that only gives me one dict per key col and not all the rows that have the key col.

Is there a way to do this ?

Upvotes: 1

Views: 283

Answers (1)

jezrael
jezrael

Reputation: 863166

Use custom lambda function in GroupBy.apply:

d = df.set_index('id').groupby('id').apply(lambda x: x.to_dict('records')).to_dict()
print (d)

{
    1718: [{
        'article_id': 202860,
        'brand': 364,
        'brand_name': 'epigamia',
        'category': 1402,
        'category_name': 'perishables'
    }, {
        'article_id': 203777,
        'brand': 364,
        'brand_name': 'epigamia',
        'category': 1402,
        'category_name': 'perishables'
    }],
    1721: [{
        'article_id': 200421,
        'brand': 751,
        'brand_name': 'milky mist',
        'category': 1402,
        'category_name': 'perishables'
    }, {
        'article_id': 200422,
        'brand': 751,
        'brand_name': 'milky mist',
        'category': 1402,
        'category_name': 'perishables'
    }]
}

Upvotes: 2

Related Questions