To convert Python Dictionary to DataFrame, you can use the pd.DataFrame.from_dict() function. Creating of DataFrame object is done from a dictionary by columns or by index allowing the datatype specifications.
Pandas DataFrame from_dict()
Pandas.DataFrame from_dict() function is used to construct a DataFrame from a given dict of array-like or dicts. By default, it is by columns. When we do column-based orientation, it is better to do it with the help of the DataFrame constructor.
Syntax
pd.DataFrame.from_dict(data, orient=’columns’, dtype=None)
Parameters
The from_dict() function takes three parameters.
- data: This is the first parameter of the method which we want to convert into a DataFrame from the input Dictionary.
- orient: It is the second parameter. It can have two values ‘columns’ or ‘index’. It depends on the type of orientation we want. If the keys are passed dictionary should be the columns of the resulting DataFrame, hence we should pass ‘columns’ which is set by default. In other cases where keys are passed in rows, we pass ‘index’ in the orientation parameter. If it’s used with columns orientation, ValueError is raised.
- dtype: By default, it is None. We use the dtype parameter if we want to force a particular datatype to the resulting DataFrame.
Example program on pandas.DataFrame.from_dict()
Write a program to show the working of pandas.DataFrame.from_dict().
import pandas as pd data = {'Name': ['Rohit', 'Raj', 'Shubh', 'Shivam'], 'Marks': [95, 74, 84, 26]} df = pd.DataFrame.from_dict(data) print(df) print(type(df))
Output
Name Marks 0 Rohit 95 1 Raj 74 2 Shubh 84 3 Shivam 26 <class 'pandas.core.frame.DataFrame'>
In the above program, we can see that we have created a dictionary consisting of Name and Mark of students then converted the Dictionary to DataFrame.
We have also printed the type of df using type() method in Python.
Example 2: Write a program to show the working of from_dict() bypassing Keys in rows hence setting the orientation to index-wise.
import pandas as pd data = {'Name': ['Rohit', 'Raj', 'Shubh', 'Shivam'], 'Marks': [95, 74, 84, 26]} df = pd.DataFrame.from_dict(data, orient='index') print(df)
Output
0 1 2 3 Name Rohit Raj Shubh Shivam Marks 95 74 84 26
Here we can see that if we orient the DataFrame in index wise, then we are getting Name and Marks in a single column and all the other data according to it.
Assigning Labels to DataFrame Columns
We can assign the labels to DataFrame Columns when converted to Dict with index orientation.
import pandas as pd data = {'Name': ['Rohit', 'Raj', 'Shubh', 'Shivam'], 'Marks': [95, 74, 84, 26]} df = pd.DataFrame.from_dict(data, columns=['A', 'B', 'C', 'D'], orient='index') print(df)
Output
A B C D Name Rohit Raj Shubh Shivam Marks 95 74 84 26
In this example, we have defined A, B, C, D labels for columns.
That is it for the Pandas DataFrame from_dict() method.