Python | Creating DataFrame from dict of narray / lists



Let`s try to understand this better with a few examples.

Code # 1:

# Python code demonstrates creating
# DataFrame from dict narray / lists
# Default address.

 

import pandas as pd 

 
# initialize the list data.

data = { ` Category` : [ `Array` , `Stack` , ` Queue` ],

  ` Marks` : [ 20 , 21 , 19 ]} 

 
# Create DataFrame

df = pd.DataFrame (data) 

  
# Print the output.

print (df)

Exit :

 Category Marks 0 Array 20 1 Stack 21 2 Queue 19 

Note: To create a DataFrame from an array / list reference, all arrays must be the same length. If an index is passed, then the length index must be equal to the length of the arrays. If no index is passed, then by default the index will be range (n), where n — array length.

Code # 2:

# Python code demonstrates creation
# DataFrame from dict narray / lists
# Default addresses.

 

import pandas as pd 

 
# initialize list data.

data = { ` Category` : [ `Array` , ` Stack` , `Queue` ],

  `Student_1` : [ 20 , 21 , 19 ], `Student_2` : [ 15 , 20 , 14 ]} 

 
# Create DataFrame

df = pd. DataFrame (data) 

 
# Print the output.

print (df.transpose ())

Exit :

 0 1 2 Category Array Stack Queue Studen t_1 20 21 19 Student_2 15 20 14 

Code # 3: Provide a list of indexes for a data frame

# Python code demonstrates creating
# DataFrame from dict narray / lists
# Default address.

 

import pandas as pd 

 
# initialize list data.

data = { ` Area` : [ `Array` , `Stack` , ` Queue` ],

`Student_1` : [ 20 , 21 , 19 ], `Student_2 ` : [ 15 , 20 , 14 ]} 

 
# Create DataFrame

df = pd.DataFrame (data, index = [ `Cat_1` , `Cat_2` , ` Cat_3` ]) 

 
# Print the output.

print (df)

Exit :

 Area Student_1 Student_2 Cat_1 Array 20 15 Cat_2 Stack 21 20 Cat_3 Queue 19 14