user2246905 user2246905 - 1 month ago 4
Python Question

List of dictionaries into dataframe python

I created some lists from some data and put them in the following way:

mylist1 =[{'vote1':{'john':'Y','peter':'Y'}}]
mylist2 =[{'vote2':{'john':'N','peter':'Y', 'david':'N'}}]
mylist1.extend(mylist2)


I want to create a dataframe from this so that it should be like this:

Name vote1 vote2
john Y N
peter Y Y
david NaN N


I tried with

pd.DataFrame(mylist1)


but of course is not working. How could I do that?

Also I could rearrange the lists in a different form (since I´m creating them) if that would make things easier. However I´m creating the list and extending it inside a long loop, so I couldn't know all the names ex ante, the new names just would start appearing in the loop.

Answer

You're better off making just one dict of dicts:

In [5]: d = {'vote1': {'john': 'Y', 'peter': 'Y'}, 'vote2': {'john':'N','peter':'Y', 'david':'N'}}

In [6]: pd.DataFrame.from_dict(d)
Out[6]:
      vote1 vote2
david   NaN     N
john      Y     N
peter     Y     Y
Comments