How to create an empty DataFrame with column names in Python?

Python DataFrame is a data structure involving 2-dimensional labels of different data types in tabular format. For easy understanding, you can simply compare it with structured SQL tables or even excel sheets consisting of rows and columns. It is one of the most popular and widely used objects of the Pandas library.
In this tutorial, you will learn how to create an empty DataFrame with column names in python.

Creating a DataFrame in Python: An example

An example for a Python DataFrame:

import pandas as pd
df=pd.DataFrame()
print(df)
Empty DataFrame
Columns: []
Index: []

Checking if a DataFrame is empty or not

You can use the empty attribute to easily validate if the DataFrame specified is empty or not. The same is shown below.

import pandas as pd
df=pd.DataFrame()
print(df)
df.empty
Empty DataFrame
Columns: []
Index: []
True

Creating an empty DataFrame with column names

The examples defined above created an empty DataFrame by calling the pandas’ DataFrame constructor.
Let us now learn how to define an empty DataFrame with column names in Python.

import pandas as pd
df = pd.DataFrame(columns = ["Col-1", "Col-2", "Col-3","Col-4"])
print(df)
df
Empty DataFrame
Columns: [Col-1, Col-2, Col-3, Col-4]
Index: []
Col-1Col-2Col-3Col-4

 

You can also pass all the column names as a list. The same is shown below:

import pandas as pd
cols=["Col-1", "Col-2", "Col-3","Col-4"]
df = pd.DataFrame(columns=cols)
print(df)
df
Empty DataFrame
Columns: [Col-1, Col-2, Col-3, Col-4]
Index: []
Col-1Col-2Col-3Col-4

Creating an empty DataFrame with column names and specified data types

When you create an empty DataFrame with columns in Python, the types of the columns are assigned as string/object by default.

import pandas as pd
df = pd.DataFrame(columns = ["Col-1", "Col-2", "Col-3","Col-4"])
print(df)
print(df.dtypes)
Empty DataFrame
Columns: [Col-1, Col-2, Col-3, Col-4]
Index: []
Col-1    object
Col-2    object
Col-3    object
Col-4    object
dtype: object

Let us now see how we can explicitly specify the data types for the columns.

Leave a Reply

Your email address will not be published.