Home > OS >  How to convert dictionary to pandas DataFrame in Python when dictionary value is a List?
How to convert dictionary to pandas DataFrame in Python when dictionary value is a List?

Time:06-29

I want to convert Python dictionary into DataFrame. Dictionary value is a List with different length.

Example:

import pandas as pd

data = {'A': [1], 'B': [1,2], 'C': [1,2,3]}

df = pd.DataFrame.from_dict(data)

But, the above code doesn't work with the following error:

ValueError: All arrays must be of the same length

The output that I would like to get is as follows:

name    value    
'A'      [1]         
'B'      [1,2]
'C'      [1,2,3] 
  

Thank you for your help.

CodePudding user response:

You can use:

df = pd.DataFrame({'name':data.keys(), 'value':data.values()})
print (df)
  name      value
0    A        [1]
1    B     [1, 2]
2    C  [1, 2, 3]

df = pd.DataFrame(data.items(), columns=['name','value'])
print (df)
  name      value
0    A        [1]
1    B     [1, 2]
2    C  [1, 2, 3]

Also working Series:

s = pd.Series(data)

print (s)
A          [1]
B       [1, 2]
C    [1, 2, 3]
dtype: object
  • Related