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
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
import pandas as pd df = pd.DataFrame({'Col-1': pd.Series(dtype='str'),'Col-2': pd.Series(dtype='int'),'Col-3': pd.Series(dtype='double'),'Col-4': pd.Series(dtype='float')}) print(df.dtypes)
Col-1 object Col-2 int32 Col-3 float64 Col-4 float64 dtype: object
Here, in order to assign data types to the columns, we make use of a dictionary format. That is, we pass the column names as key and the column types as value.
Note:
- You can use the shape attribute in order to determine the size of the DataFrame.
import pandas as pd df = pd.DataFrame(columns = ["Col-1", "Col-2", "Col-3","Col-4"]) print(df) df.shape
Empty DataFrame
Columns: [Col-1, Col-2, Col-3, Col-4]
Index: []
(0, 4) - You can use the list() method in order to get the columns of a DataFrame.
import pandas as pd df = pd.DataFrame(columns = ["Col-1", "Col-2", "Col-3","Col-4"]) list(df)
['Col-1', 'Col-2', 'Col-3', 'Col-4']
Also read,DataFrame, date_range(), slice() in Python Pandas library
Leave a Reply