Pandas DataFrame from_dict() – Dictionary to DataFrame

Filed Under: Python
Pandas Dataframe From Dict

Pandas DataFrame from_dict() method is used to convert Dict to DataFrame object. This method accepts the following parameters.

  • data: dict or array like object to create DataFrame.
  • orient: The orientation of the data. The allowed values are (‘columns’, ‘index’), default is the ‘columns’.
  • columns: a list of values to use as labels for the DataFrame when orientation is ‘index’. If it’s used with columns orientation, ValueError is raised.

Pandas DataFrame from_dict() Examples

Let’s look at some examples to convert dict to DataFrame object.

1. Simple Example to create DataFrame from Dict


import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame.from_dict(d1)

print(df)

Output:


     Name  ID
0  Pankaj   1
1    Lisa   2

2. Creating DataFrame from Dict with index orientation


import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame.from_dict(d1, orient='index')

print(df)

Output:


           0     1
Name  Pankaj  Lisa
ID         1     2

3. Assigning Labels to DataFrame Columns when converted Dict with index orientation


import pandas as pd

d1 = {'Name': ['Pankaj', 'Meghna'], 'ID': [1, 2], 'Role': ['CEO', 'CTO']}

df = pd.DataFrame.from_dict(d1, columns=['A', 'B'], orient='index')

print(df)

Output:


           A       B
Name  Pankaj  Meghna
ID         1       2
Role     CEO     CTO

When to use DataFrame from_dict() method?

We can convert dictionary to DataFrame using its constructor too.


import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame(d1)
print(df)

Output:


     Name  ID
0  Pankaj   1
1    Lisa   2

But, there is no option to use index-based orientation.

So, when you want index orientation, use from_dict() method. For default scenarios, you are better off with the DataFrame constructor.

References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages