Creating a Pandas DataFrame

In the real world, a Pandas DataFrame will be created by loading datasets from an existing store, the store can be SQL database, CSV file and Excel file. Pandas DataFrame can be created from lists, dictionary, dictionary list, etc.

Data frame — it is a two-dimensional data structure, that is, the data is aligned in a tabular form by rows and columns. With datasets arranged in rows and columns, we can store any number of datasets in a data frame. We can do a lot of operations on these datasets like arithmetic, column / row selection, column / row addition, etc.

DataFrame pandas can be created in several ways. Let`s discuss the different ways to create a DataFrame one by one.

Create an empty data frame:
The main DataFrame that can be created is an Empty DataFrame. An empty Dataframe is created by simply calling the Dataframe constructor.

# import pandas as pd

import pandas as pd

 
# Call the DataFrame constructor

df = pd.DataFrame ()

 

print (df)

Output:

 Empty DataFrame Columns: [] Index: [] 

Create dataframe using List :
DataFrame can be created using one list or a list of lists.

# import pandas as pd

import pandas as pd

 
# list lines

lst = [ `Geeks` , ` For` , ` Geeks` , `is`

`portal` , `for` , ` Geeks` ]

 
< code class = "comments"> # Call the DataFrame constructor in the list

df = pd.DataFrame (lst)

print (df)

Output:

Create a DataFrame from a ndarray / lists reference :
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.

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

 

import pandas as pd

 
# initialize the list data.

data = { `Name` : [ ` Tom` , `nick` , `krish` , ` jack` ], `Age` : [ 20 , 21 , 19 , 18 ]}

 
# Create DataFrame

df = pd.DataFrame (data)

 
# Print the output.

print (df)

Output:

# import pandas as pd

import pandas as pd

 
# list dictionary

dict = { `name` : [ " aparna " , " pankaj " , "sudhir" , "Geeku" ],

`degree` : [ "MBA" , "BCA" , "M .Tech " , " MBA " ],

`score` : [ 90 , 40 , 80 , 98 ]}

 

df = pd.DataFrame ( dict )

 

print (df)

Output:

Several ways to create a data frame: