0

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!

Shiva
  • 212
  • 2
  • 11
  • Does this answer your question? [Convert Python dict into a dataframe](https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe) – Mahrkeenerh Oct 21 '21 at 20:59
  • 1
    @Mahrkeenerh No it doesn't. Mine is a different case than the post you have tagged me to. Please do look at it and notice the difference. Thank you. – Shiva Oct 21 '21 at 21:01
  • The current issue is that `cols` is not a valid structure in `python`. But assuming it were, you can probably just flatten and then build -> `df = pd.DataFrame({k: v for d in cols for k, v in d.items()})` [How do I merge a list of dicts into a single dict?](https://stackoverflow.com/a/3495395/15497888) – Henry Ecker Oct 21 '21 at 21:01
  • @HenryEcker I have edited the question. The values are all string datatypes except NaN. – Shiva Oct 21 '21 at 21:07

1 Answers1

2
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()})
11_22_33
  • 116
  • 1
  • 15