Here are six ways to create an empty DataFrame in Pandas:
- Without rows and columns
- With only columns
- With column names and indices
- Using reindex() on an existing DataFrame
- Using copy() on an existing DataFrame
- Using DataFrame constructor with dtype
Method 1: Without rows and columns
You can create a DataFrame with no rows and no columns by simply instantiating a DataFrame without passing any arguments.
import pandas as pd
df_empty = pd.DataFrame()
print(df_empty)
Output
Empty DataFrame
Columns: []
Index: []
Method 2: With only columns
To create an empty DataFrame with column names but no rows, pass a list of column names to the DataFrame constructor.
import pandas as pd
columns = ['Column1', 'Column2', 'Column3']
df_empty_with_columns = pd.DataFrame(columns=columns)
print(df_empty_with_columns)
Output
Empty DataFrame
Columns: [Column1, Column2, Column3]
Index: []
Method 3: With column names and indices
If you want to specify column names and row indices (but still have no data), you can pass the column names as before and specify an index parameter.
import pandas as pd
columns = ['Column1', 'Column2', 'Column3']
index = ['Row1', 'Row2', 'Row3']
df_empty_with_columns_and_index = pd.DataFrame(columns=columns, index=index)
print(df_empty_with_columns_and_index)
Output
Method 4: Using reindex() on an existing DataFrame
You can use the reindex() method on the existing DataFrame with an empty list to create an empty DataFrame.
import pandas as pd
existing_df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
new_empty_df = existing_df.reindex([])
print(new_empty_df)
Output
Empty DataFrame
Columns: [A, B]
Index: []
Method 5: Using copy() on an existing DataFrame
If you have an existing DataFrame and want to create a new empty DataFrame with the same structure (column names and data types), you can use the copy method with the deep=False argument and drop all rows.
This approach keeps the column structure and data types but removes the data.
import pandas as pd
existing_df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
new_empty_df = existing_df.copy(deep=False)
new_empty_df.drop(new_empty_df.index, inplace=True)
print(new_empty_df)
Output
Empty DataFrame
Columns: [A, B]
Index: []
Method 6: Using DataFrame constructor with dtype
If you want to specify the data types for the empty columns, you can use the DataFrame constructor with the dtype argument.
This is specifically helpful when you know the data types of the columns in advance.
import pandas as pd
empty_df = pd.DataFrame(columns=["col1", "col2"], dtype=float)
print(empty_df)
Output
Empty DataFrame
Columns: [col1, col2]
Index: []
That’s all!