Pandas Dataframe allows you to store data in rows and column format.
You can create empty dataframe with only column names using the pd.DataFrame(columns = column_names_as_list) statement.
Basic Example
import pandas as pd
column_names = ["Col 1", "Col 2", "Col 3"]
df = pd.DataFrame(columns = column_names)
df
- The column names are passed as a list to the
columns
property.
This tutorial teaches you how to create an empty dataframe with only column names using the pd.Dataframe()
constructor.
Table of Contents
Create an empty DataFrame with ONLY column names
You can create an empty pandas dataframe with only column names using the pd.Dataframe() constructor.
- The constructor accepts the column names using the
columns
property. - Pass column names in an array-like object
Code
The below code demonstrates how to create an empty dataframe with ONLY column names.
- The column names are assigned to the list
column_names
- This list is passed to the
columns
parameter in the dataframe constructor
import pandas as pd
column_names = ["Col 1", "Col 2", "Col 3"]
df = pd.DataFrame(columns = column_names)
df
An empty dataframe will be created with the column names.
Dataframe Will Look Like
Col 1 | Col 2 | Col 3 |
---|
Create an empty DataFrame with column names from another dataframe
To create an empty dataframe with column names from another dataframe,
- Get the column names of another dataframe using the
df.columns
statement - Pass it to the
columns
attribute in the dataframe constructor
Code
df2 = pd.DataFrame(columns = df.columns)
df2
Dataframe Will Look Like
Col 1 | Col 2 | Col 3 |
---|
Create Empty Dataframe With Column names And Column Types
To create an empty dataframe with column names and column types,
- create an empty series with desired
dtype
- Assign it to the column names.
If you want to change the column type after creating the dataframe, read How to Change column type in pandas.
Code
The below code demonstrates how to create an empty dataframe with column names and column types.
df = pd.DataFrame({'Col 1': pd.Series(dtype='str'),
'Col 2': pd.Series(dtype='int'),
'Col 3': pd.Series(dtype='float')})
df.dtypes
You can print the dataframe types using the df.dtypes
to see the data type of the columns.
Output
Col 1 object
Col 2 int64
Col 3 float64
dtype: object