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, we can use DataFrame() constructor.

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()

print(df)
Run

Output

Empty DataFrame
Columns: []
Index: []

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

Example 2: Create DataFrame from List of Lists

To initialize a DataFrame from list of lists, you can pass this list of lists to pandas.DataFrame() constructor as data argument.

In this example, we will create a DataFrame for list of lists.

Python Program

import pandas as pd

#list of lists
data = [['a1', 'b1', 'c1'],
        ['a2', 'b2', 'c2'],
        ['a3', 'b3', 'c3']]

df = pd.DataFrame(data)
print(df)
Run

Output

   0  1  2
0  a  b  c
1  d  e  f
2  g  h  i
3  j  k  l

Example 3: Create DataFrame from Dictionary

To initialize a DataFrame from dictionary, pass this dictionary to pandas.DataFrame() constructor as data argument.

In this example, we will create a DataFrame for list of lists.

Python Program

    0   1   2
0  a1  b1  c1
1  a2  b2  c2
2  a3  b3  c3
Run

Output

   aN  bN  cN
0  a1  b1  c1
1  a2  b2  c2
2  a3  b3  c3

Summary

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