Pandas Create Empty DataFrame


There are scenarios where you may need to create an empty DataFrame as a starting point and append rows to it later.

In this article, you will learn different ways to create an empty DataFrame in Pandas.

    Table of Contents

  1. Using pd.DataFrame() Constructor
  2. From an Existing DataFrame
  3. Defining Columns in an Empty DataFrame
  4. Creating an Empty DataFrame with Specified Index
  5. Conclusion

1. Using pd.DataFrame() Constructor

pandas.DataFrame() is a constructor that is used to create dataframes in pandas.

It takes a variety of arguments to create a dataframe, but if you pass no arguments, it will create an empty dataframe.

import pandas as pd

# 👇 Creating an empty DataFrame
df_empty = pd.DataFrame()

print(df_empty)

Output:

Empty DataFrame
Columns: []
Index: []

Also, learn how to check if a dataframe is empty.


2. Create an Empty DataFrame from an Existing DataFrame

Suppose you have an existing Dataframe and you want to create an empty dataframe with the same columns of the DataFrame, you can do it by applying head(0) chained with copy() method on the existing dataframe.

Here head(0) returns the first 0 rows of the dataframe (basically column names) and copy() method creates a copy of the dataframe.

import pandas as pd

# Existing DataFrame
df_existing = pd.DataFrame({'A': [1, 2, 3],
                            'B': ['X', 'Y', 'Z']})

# 👇 Creating an empty DataFrame with the same columns
df_empty = df_existing.head(0).copy()

print(df_empty)

Output:

Empty DataFrame
Columns: [A, B]
Index: []

3. Defining Columns in an Empty DataFrame

When you create an empty dataframe, it will have no columns. You can define the columns of an dataframe by passing a list of column names to the columns parameter of pd.DataFrame() constructor.

the following example creates an empty dataframe and set 'A' and 'B' as column.

import pandas as pd

# 👇 Creating an empty DataFrame with columns
df_empty = pd.DataFrame(columns=['A', 'B'])

print(df_empty)

Output:

Empty DataFrame
Columns: [A, B]
Index: []

4. Creating an Empty DataFrame with Specified Index

By default, an empty dataframe will have no index. You can specify the index of an empty dataframe by passing a list of index values to the index parameter of pd.DataFrame() constructor.

The following example creates an empty dataframe with index values 'a', 'b', 'c'.

import pandas as pd

# 👇 Creating an empty DataFrame with index
df_empty = pd.DataFrame(index=['a', 'b', 'c'])

print(df_empty)

Output:

Empty DataFrame
Columns: []
Index: [a, b, c]

Conclusion

Now you know how to create an empty Dataframe of any type. You can start with your empty canvas of a dataframe and do whatever you want to do with it.

Happy Learning!