Shiva
Shiva

Reputation: 312

Several dictionaries in a list to columns of a dataframe

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!

Upvotes: 0

Views: 49

Answers (1)

11_22_33
11_22_33

Reputation: 86

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()})

Upvotes: 2

Related Questions