Home > database >  Turning a list of dictionaries into a DataFrame
Turning a list of dictionaries into a DataFrame

Time:01-05

If you have a list of dictionaries like this:

listofdict = [{'value1': [1, 2, 3, 4, 5]}, {'value2': [5, 4, 3, 2, 1]}, {'value3': ['a', 'b', 'c', 'd', 'e']}]

How can you turn it into a dataframe where value1, value2 and value3 are column names and the lists are the columns.

I tried:

df = pd.DataFrame(listofdict)

But it gives me the values congested in one row and the remaining rows as NaN.

CodePudding user response:

DataFrame is expecting a single dictionary with column names as keys, so you need to fusion all these dictionaries in a single one like {'value1': [1, 2, 3, 4, 5], 'value2': [5, 4, 3, 2, 1], ... }

You can try

listofdict = [{'value1':[1,2,3,4,5]}, {'value2':[5,4,3,2,1]},{'value3':['a','b','c','d','e']}]

dicofdics = {}

for dct in listofdict:
    dicofdics.update(dct)

df = pd.DataFrame(dicofdics)
df
index value1 value2 value3
0 1 5 a
1 2 4 b
2 3 3 c
3 4 2 d
4 5 1 e

CodePudding user response:

Here is another way:

df = pd.DataFrame({k:v for i in listofdict for k,v in i.items()})

Output:

   value1  value2 value3
0       1       5      a
1       2       4      b
2       3       3      c
3       4       2      d
4       5       1      e
  • Related