Home > Blockchain >  Convert Dataframe from a dictionary list
Convert Dataframe from a dictionary list

Time:10-24

I have a dictionary list:

orderlist = [
                {
                'order_id': 5,
                'status': 'completed',
                'line_items': [{'product_id': 6,'name': 'headphone'} , {'product_id': 7,'name': 'airbuds'} ]
                },

                {
                'order_id': 6,
                'status': 'pending',
                'line_items': [{'product_id': 8,'name': 'smartwatch'} , {'product_id': 9,'name': 'smartphone'} ]
                },

            ]

and I want this dataframe:

order_id        status      product_id          name 
    5          completed        6               headphone
    5          completed        7               airbuds
    6          pending          8               smartwatch
    6          pending          9               smartphone

I have tried it like this:

df_order = pd.DataFrame(orderlist)

The problem is that I didn't get my desired dataframe.

CodePudding user response:

You can use pd.json_normalize:

df = pd.json_normalize(orderlist, ['line_items'], ['order_id', 'status'])
print(df)

Output:

   product_id        name order_id     status
0           6   headphone        5  completed
1           7     airbuds        5  completed
2           8  smartwatch        6    pending
3           9  smartphone        6    pending
  • Related