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

Mohammad

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.

jezrael

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to replace value in a dataframe and convert it to a list of dictionary in python pandas

Convert list type dictionary to pandas dataframe - python

How to convert list of nested dictionary to pandas DataFrame?

How to convert python dictionary to dataframe in pandas

How to convert a python dictionary with tuples into a pandas dataframe?

How to convert python dictionary to pandas dataframe

Convert dictionary with list into pandas dataframe

Convert a dictionary value to a pandas Dataframe

How to convert list to dictionary in python with key value?

Convert Python Dictionary to Pandas Dataframe

Python dictionary of list to Pandas dataframe

How to convert dictionary to dataframe when values of keys are list of list?

convert json data to pandas dataframe in python (dictionary inside list )

How to convert a nested dictionary with a list inside to a Pandas DataFrame?

How to convert dataframe into dictionary python

How to convert dictionary to dataframe in Python

Convert Dictionary of List of Dictionaries to a Pandas Dataframe

Convert a list of dictionary containing dictionaries into Pandas dataframe

Convert a dictionary of a list of dictionaries to pandas DataFrame

convert list of value in nested dictionary to dataframe

python dictionary and list: how to convert it?

how to convert a list to dictionary in python?

How to convert list to dictionary in Python?

ValueError when trying to convert Dictionary to DataFrame Pandas

Convert a Pandas DataFrame to a dictionary

Convert dictionary into Pandas dataframe

Convert Dictionary to Pandas DataFrame

Convert a dictionary to pandas dataframe

How to use python to convert nested dictionary to pandas DataFrame