Home > Mobile >  How to create a dataframe from a nested dictionary using pandas?
How to create a dataframe from a nested dictionary using pandas?

Time:10-09

I have the following nested dictionary:

dict1 = {'a': 1,'b': 2,'remaining': {'c': 3,'d': 4}}

I want to create a dataframe using pandas in order to achieve the following

df = pd.DataFrame(columns=list('abcd'))
df.loc[0] = [1,2,3,4]

CodePudding user response:

You could pop the 'remaining' dict to update dict1, then convert the values to vectors (like lists).

nested = dict1.pop('remaining')
dict1.update(nested)

pd.DataFrame({k: [v] for k, v in dict1.items()})
    a   b   c   d
0   1   2   3   4

CodePudding user response:

You can use pandas.json_normalize:

dict1 = {'a': 1,'b': 2,'remaining': {'c': 3,'d': 4}}

df = pd.json_normalize(dict1)
df.columns = list('abcd')

Result:

   a  b  c  d
0  1  2  3  4
  • Related