How to Mock DataFrame Schema Columns in Python
Create an empty pandas DataFrame with only the specified column names to mock a schema before any data is loaded.
pip install pandas
Python code
10 linesimport pandas as pd
def mock_schema(columns):
return pd.DataFrame(columns=columns)
if __name__ == "__main__":
cols = ["name", "age", "city"]
df = mock_schema(cols)
print(df)
print(f"Columns: {list(df.columns)}, Shape: {df.shape}")
Output
Empty DataFrame
Columns: [name, age, city]
Index: []
Columns: ['name', 'age', 'city'], Shape: (0, 3)
How it works
The pd.DataFrame(columns=columns) constructor creates a DataFrame with zero rows and the provided column names. Because no index is supplied, pandas assigns an empty RangeIndex. This pattern is useful for schema validation, unit testing, or as a template before filling with actual data. The shape of the resulting DataFrame is (0, 3) — zero rows and three columns, matching the schema exactly.
Common mistakes
- Forgetting to import pandas, leading to a NameError.
- Passing a tuple instead of a list for columns, which works but is less conventional.
- Expecting the DataFrame to have a default index with rows; it has zero rows until you add data.
- Using `pd.DataFrame(columns=set(...))` with a set, which can produce nondeterministic column order.
Variations
- Use `pd.DataFrame(columns=cols, index=pd.RangeIndex(0))` to explicitly set the index shape.
- Create a schema from a dictionary of column names to dtypes using `pd.DataFrame({col: pd.Series(dtype=dtype) for col, dtype in schema.items()})`.
Real-world use cases
- Writing unit tests for data transformation functions that expect a DataFrame with a given schema.
- Defining an empty DataFrame as an output template in a data pipeline before processing streaming rows.
- Validating pandas operations against a set of expected columns when building schema-aware ETL jobs.
Sponsored
More from Big data & Spark
Keep learning
Related tutorials and quizzes for this topic.