Pandas DataFrame is a 2-dimensional labeled data structure like any table with rows and columns. The size and values of the dataframe are mutable, i.e., can be modified. It is the most commonly used pandas object. Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let’s discuss different ways to create a DataFrame one by one.
Method #1: Creating DataFrame using dictionary of lists
With this method in Pandas, we can transform a dictionary of lists into a dataframe.
Python3
# importing pandas as pd import pandas as pd # dictionary of lists dict = { 'name' :["aparna", "pankaj", "sudhir", "Geeku"], 'degree' : ["MBA", "BCA", "M.Tech", "MBA"], 'score' :[ 90 , 40 , 80 , 98 ]} df = pd.DataFrame( dict ) df |
Output: As is evident from the output, the keys of a dictionary is converted into columns of a dataframe whereas the elements in lists are converted into rows.
Adding index to a dataframe explicitly:
Python3
import pandas as pd # dictionary of lists dict = { 'name' :[ 'aparna' , 'pankaj' , 'sudhir' , 'Geeku' ], 'degree' : [ 'MBA' , 'BCA' , 'M.Tech' , 'MBA' ], 'score' :[ 90 , 40 , 80 , 98 ]} df = pd.DataFrame( dict ,index = [ 'Rollno1' , 'Rollno2' , 'Rollno3' , 'Rollno4' ]) df |
Output:
Method #2: Using from_dict() function
Python3
# importing pandas as pd import pandas as pd # dictionary of lists dict = { 'name' :["aparna", "pankaj", "sudhir", "Geeku"], 'degree' : ["MBA", "BCA", "M.Tech", "MBA"], 'score' :[ 90 , 40 , 80 , 98 ]} df = pd.DataFrame.from_dict( dict ) df |
Output:
Method#3 : Creating dataframe by passing lists variables to dictionary
Python3
import pandas as pd # dictionary of lists name = [ 'aparna' , 'pankaj' , 'sudhir' , 'Geeku' ] degree = [ 'MBA' , 'BCA' , 'M.Tech' , 'MBA' ] score = [ 90 , 40 , 80 , 98 ] dict = { 'name' :name, 'degree' :degree , 'score' :score} df = pd.DataFrame( dict ,index = [ 'Rollno1' , 'Rollno2' , 'Rollno3' , 'Rollno4' ]) df |
Output: