Sometimes We want to create an empty dataframe for saving memory. For example, I want to add records of two values only rather than the whole dataframe. Then I will create an empty dataframe first and then append the values to it one by one. In this entire tutorial, I will show you how to create an empty dataframe in Python using pandas.
Step by Step to create an empty dataframe
Step 1: Import all the necessary libraries.
In our example, We are using three python modules. And that is NumPy, pandas, and DateTime. Let’s import all of them.
import numpy as np import pandas as pd import datetime
Step 2: Follow the Example to create an empty dataframe.
Example 1: Creating a Simple Empty Dataframe.
In this example, I will first make an empty dataframe. Then after I will append each row one by one.
Execute the following lines of code.
#creation of empty Dataframe df = pd.DataFrame(columns=['A', 'B', 'C'], index=range(5)) #appending rows df.loc = [1, 2, 3] df.loc = [4, 5, 6]
In the same way you can add other rows according to you your requirements.
You will get the following output.
Empty Dataframe Output
Addition of Rows to the Empty Dataframe
Example 2: Creating a Time Series Empty Dataframe.
The first example was basic. Now lets move to advance. Here I will create a time series empty dataframe. After that, I will add values to each row.
Creation of Empty Time-Series Dataframe.
todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns = ['A','B', 'C'] df = pd.DataFrame(index=index, columns=columns)
Here I am first getting Today’s date and then using it I am creating an index list of 10 elements. You can do so by pandas.date_range() method.
If you print the output of the above code, then you will get three columns with the 10 rows.
Now you can add any data or records here. For example, I can fill all the rows with 0 using the df.fillna(0).
The output of the dataframe after applying it is the below.
The other thing I can do is creating and adding dataset to the columns. To do so let’s create a dummy dataset. I will create it using the numpy.arange() method and then transposing it to convert it to columns.
Run the code to create it.
data = np.array([np.arange(10)]*3).T
After it , pass this data as an argument inside the pd.Dataframe() Method.
df = pd.DataFrame(data, index=index, columns=columns)
When you will print the dataframe you will get the following output.
These are examples to create an empty dataframe. Hope you have liked this tutorial. If you have any queries then you can contact us Offical Facebook Page.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.