To create an empty DataFrame with pandas in Python, you can use the DataFrame() function.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(empty_dataframe)
#Output:
Empty DataFrame
Columns: []
Index: []
When working with the pandas in Python, the main data structure which is the DataFrame.
Depending on the program you are designing, you might need to create an empty DataFrame.
Creating an empty pandas DataFrame is easy. To create an empty DataFrame with pandas in Python, you can use the DataFrame() function.
Below shows you how to create an empty pandas DataFrame in Python.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(empty_dataframe)
#Output:
Empty DataFrame
Columns: []
Index: []
Properties of Empty pandas DataFrames
There are a number of properties of empty DataFrames which you should be aware of.
First, empty DataFrames do not have an index, have no columns and have no rows.
You can see this when you print an empty DataFrame to the console.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(empty_dataframe)
#Output:
Empty DataFrame
Columns: []
Index: []
Since there are no rows or columns in an empty DataFrame, the size of an empty DataFrame is 0.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(empty_dataframe.size)
#Output:
0
The length of an empty DataFrame is also 0.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(len(empty_dataframe)
#Output:
0
How to Check if pandas DataFrame is Empty
There are a few ways you can check if a DataFrame is empty.
The easiest way to check if a pandas DataFrame is empty is with the empty property.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(empty_dataframe.empty)
#Output:
True
You can also check if a DataFrame is empty by checking if the length is 0 or the length of the index is 0.
import pandas as pd
empty_dataframe = pd.DataFrame()
print(len(empty_dataframe) == 0)
print(len(empty_dataframe.index) == 0)
#Output:
True
True
Concatenating Data to Empty DataFrame in Python
One useful case where you might want to create an empty DataFrame is if you are going to create other DataFrames and then concatenate those DataFrames in a loop.
Let’s say you have a function which loops and creates new DataFrames which you want to append.
You can use the pandas concat() function to concat DataFrames to an empty DataFrame in the following way.
import pandas as pd
df = pd.DataFrame()
for x in range(0,10):
#steps creating new DataFrame named df_new
df = pd.concat([df, df_new], ignore_index=True)
Hopefully this article has been useful for you to learn how to create empty DataFrames in Python.