How to Create or Initialize a Pandas DataFrame?

Pandas DataFrame – Create or Initialize

In Python Pandas module, DataFrame is a very basic and important type. To create a DataFrame from different sources of data or other Python datatypes, you can use constructors of DataFrame() class.

In this tutorial, we will learn different ways of how to create and initialize Pandas DataFrame.

Python Pandas Create or Initialize DataFrame

Syntax of DataFrame() class

The syntax of DataFrame() class is:

DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

where all the arguments are optional and

  • data can be ndarray, iterable, dictionary or another dataframe.
  • index can be Index or an array. If no index is provided, it defaults to Range Index, i.e., 0 to number of rows – 1.
  • columns are used to label the columns
  • dtype is used to specify or force a datatype on the data. If you do not specify, dtype is inferred from the data itself.
  • copy if True, copies data from inputs. Note that this affects only DataFrame or 2d ndarray input.

Example 1: Create an Empty DataFrame

To create an empty DataFrame, pass no arguments to pandas.DataFrame() class.

In this example, we create an empty DataFrame and print it to the console output.

Python Program

import pandas as pd

df = pd.DataFrame()

Run this program


Empty DataFrame
Columns: []
Index: []

As we have provided no arguments, the columns array is empty and index array is empty.

Example 2: Create and Initialize DataFrame

To initialize a DataFrame with data, you can pass data to pandas.DataFrame() class. In this example, we create will create a DataFrame for marks of students and it contains student name and subject names as columns.

Python Program

import pandas as pd

df_marks = pd.DataFrame(
	[['Somu', 68, 84, 78, 96],
	['Kiku', 74, 56, 88, 85],
	['Amol', 77, 73, 82, 87],
	['Lini', 78, 69, 87, 92]],
	columns=['name', 'physics', 'chemistry','algebra','calculus'])

Run this program


   name  physics  chemistry  algebra  calculus
0  Somu       68         84       78        96
1  Kiku       74         56       88        85
2  Amol       77         73       82        87
3  Lini       78         69       87        92


In this Pandas Tutorial, we learned how to create an empty DataFrame, and then to create a DataFrame with data from a Python Dictionary, with the help of well detailed examples.