How to create DataFrame from dictionary in Python-Pandas?
Let’s discuss how to create DataFrame from dictionary in Pandas. There are multiple ways to do this task.
Create DataFrame from Dictionary using default Constructor of pandas.Dataframe class
Python3
import pandas as pd
details = {
'Name' : [ 'Ankit' , 'Aishwarya' , 'Shaurya' , 'Shivangi' ],
'Age' : [ 23 , 21 , 22 , 21 ],
'University' : [ 'BHU' , 'JNU' , 'DU' , 'BHU' ],
}
df = pd.DataFrame(details)
df
|
Output:
Create DataFrame from Dictionary with user-defined indexes.
Python3
import pandas as pd
details = {
'Name' : [ 'Ankit' , 'Aishwarya' , 'Shaurya' , 'Shivangi' ],
'Age' : [ 23 , 21 , 22 , 21 ],
'University' : [ 'BHU' , 'JNU' , 'DU' , 'BHU' ],
}
df = pd.DataFrame(details, index = [ 'a' , 'b' , 'c' , 'd' ])
df
|
Output:
Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value
Python3
import pandas as pd
details = {
'Ankit' : 22 ,
'Golu' : 21 ,
'hacker' : 23
}
df = pd.DataFrame( list (details.items()))
df
|
Output:
Create DataFrame from Dictionary with required columns only
Python3
import pandas as pd
details = {
'Name' : [ 'Ankit' , 'Aishwarya' , 'Shaurya' , 'Shivangi' ],
'Age' : [ 23 , 21 , 22 , 21 ],
'University' : [ 'BHU' , 'JNU' , 'DU' , 'BHU' ],
}
df = pd.DataFrame(details, columns = [ 'Name' , 'University' ])
df
|
Output:
Create DataFrame from Dictionary with different Orientation i.e. Dictionary key is act as indexes in Dataframe
Python3
import pandas as pd
details = {
'Name' : [ 'Ankit' , 'Aishwarya' , 'Shaurya' , 'Shivangi' ],
'Age' : [ 23 , 21 , 22 , 21 ],
'University' : [ 'BHU' , 'JNU' , 'DU' , 'BHU' ],
}
df = pd.DataFrame.from_dict(details, orient = 'index' )
df
|
Output:
Create DataFrame from nested Dictionary
Python3
import pandas as pd
details = {
0 : {
'Name' : 'Ankit' ,
'Age' : 22 ,
'University' : 'BHU'
},
1 : {
'Name' : 'Aishwarya' ,
'Age' : 21 ,
'University' : 'JNU'
},
2 : {
'Name' : 'Shaurya' ,
'Age' : 23 ,
'University' : 'DU'
}
}
df = pd.DataFrame(details)
df = df.transpose()
df
|
Output:
Last Updated :
29 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...