Skip to content
Advertisement

How to create a pandas dataframe from a nested dictionary with lists of dictionaries?

I have a dictionary like that:

JavaScript

I want to construct a dataframe where I can see user1 and user2 as indices, product1, product2 and product3 as columns and values of these products should be values of columns. I tried looking here and found this post Construct pandas DataFrame from items in nested dictionary, but my format of data is different and I can’t find out how to make products to be my columns. So far I get “‘product1′:10” as my value in the first column of the first row. Using orient=’index’ made my main keys as indices, but that’s it. Please, help me.

Advertisement

Answer

One option would be to merge the lists of dicts into a single dict then build a DataFrame.from_dict:

JavaScript

df:

JavaScript

Optional alphanumeric sort with natsort:

JavaScript
JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement