Home > Enterprise >  convert list of dictionaries with values in list to a dataframe
convert list of dictionaries with values in list to a dataframe

Time:03-05

How do i convert the below to a dataframe as like the expected output below? Please help. I tried other answers of SO but they were in different format of input.

ab = [{'q1':[7,2,6]},{'q2':[1,2,3]}]

import pandas as pd
pd.DataFrame(ab)

Current output:

    q1  q2
0   [7, 2, 6]   NaN
1   NaN [1, 2, 3]

Expected Output

    q1  q2
0   7   1
1   2   2
2   6   3

CodePudding user response:

A simple transformation:

ds = {k: v for d in ab for k, v in d.items()}
df = pd.DataFrame(ds)

CodePudding user response:

Other options.

Using pandas.concat:

df = pd.concat(map(pd.DataFrame, ab), axis=1)

or using collections.ChainMap:

from collections import ChainMap
df = pd.DataFrame(dict(ChainMap(*ab)))

output:

   q1  q2
0   7   1
1   2   2
2   6   3
  • Related