Home > other >  Several dictionaries in a list to columns of a dataframe
Several dictionaries in a list to columns of a dataframe

Time:10-22

I have a sample of list of dictionaries as given below

NaN = np.nan
cols = [ {'A':['Orange', 'Lemon', NaN, 'Peach']},
         {'B':['Tiger', NaN, NaN, 'Lion']},
         {'C':['London', 'New York', 'Bangalore', NaN]},
         {'D':['Cricket', 'BaseBall', 'Football', 'Tennis']}
       ]

I want to convert this to columns of dataframe. The keys of the dictionary should be the column name. The values should be the corresponding rows of the dataframe.

The final output should look like the image shown below.

enter image description here

Any help is greatly appreciated. Thank you!

CodePudding user response:

import pandas as pd

cols = [ {'A':['Orange', 'Lemon', 'NaN', 'Peach']},
         {'B':['Tiger', 'NaN', 'NaN', 'Lion']},
         {'C':['London', 'New York', 'Bangalore', 'NaN']},
         {'D':['Cricket', 'BaseBall', 'Football', 'Tennis']}
       ]
       
df = pd.DataFrame({k: v for d in cols for k, v in d.items()})
  • Related