Contents:
Create Pandas DataFrame from Python Dictionary
You can create a DataFrame from a Dictionary by passing the dictionary as data arguments to the DataFrame() class.
In this tutorial, we will learn how to create Pandas DataFrame from Python Dictionary.
Syntax – Create DataFrame
The syntax to create a DataFrame from a dictionary object is shown below.
mydataframe = DataFrame(dictionary)
Each element in the dictionary is translated to a column, where the key is the column name and the values array is the column value.
Example 1: Create DataFrame from Dictionary
In the following example, we will create a dictionary and pass this dictionary as the data argument to the DataFrame() class.
Python Program
import numpy as np
import pandas as pd
mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]}
#create dataframe using dictionary
df_marks = pd.DataFrame(mydictionary)
print(df_marks)
Output
names physics chemistry algebra
0 Geo 68 84 78
1 Kiku 74 56 88
2 Amol 77 73 82
3 Lini 78 69 87
Key values (name, physics, chemistry, algebra) are converted to column names and array of values to column values.
Example 2: Create DataFrame from Python Dictionary
In this example, we will create a DataFrame with two columns and four rows of data using a Dictionary.
Python Program
import numpy as np
import pandas as pd
mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
'roll_no': [1, 2, 3, 4]
}
#create dataframe using dictionary
df_students = pd.DataFrame(mydictionary)
print(df_students)
Output
names roll_no
0 Somu 1
1 Kiku 2
2 Amol 3
3 Lini 4
Video
Summary
In this Panda Guide we have learned how to create Pandas DataFrame from Python Dictionary with the help of detailed examples.
Hope this helps!