Create an empty DataFrame with explicit column names (df = pd.DataFrame(columns=["col1", "col2"])), or—better yet for performance—collect rows in a Python list of dictionaries or tuples first and construct the DataFrame once via pd.DataFrame(rows).
Basic Example
import pandas as pd
# 1. Recommended approach: collect rows in a list first, then build DataFrame once
rows = []
rows.append({"name": "Alice", "age": 30, "city": "Lahore"})
rows.append({"name": "Bob", "age": 25, "city": "Karachi"})
df = pd.DataFrame(rows, columns=["name", "age", "city"])
print(df)
Output:
name age city
0 Alice 30 Lahore
1 Bob 25 Karachi
Key Details & Alternative Methods
- Why collecting into a Python
listfirst is strongly recommended: Pandas DataFrames are backed by contiguous NumPy/Arrow memory arrays, not linked lists. Appending rows inside a loop withpd.concat()copies the entire DataFrame on every iteration ($O(n^2)$ time complexity), whereas appending to a Pythonlistis $O(1)$ amortized and converts to a DataFrame in a single $O(n)$ pass. - Pre-allocating an empty DataFrame with explicit data types (
dtypes): If you must start with an empty DataFrame and assign rows by index label using.loc[], specifydtypesupfront so numeric columns do not silently degrade toobjectdtype:df = pd.DataFrame({ "name": pd.Series(dtype="str"), "age": pd.Series(dtype="int64"), "score": pd.Series(dtype="float64"), }) # Populate rows by index label using .loc[] df.loc[0] = ["Alice", 30, 92.5] df.loc[1] = ["Bob", 25, 88.0] - Combining multiple DataFrames with
pd.concat(): Note thatdf.append()was removed in Pandas 2.0. When merging an existing DataFrame with one or more new rows, pass a list of DataFrames topd.concat(..., ignore_index=True):df = pd.DataFrame(columns=["name", "age"]) new_row = pd.DataFrame([{"name": "Charlie", "age": 35}]) df = pd.concat([df, new_row], ignore_index=True) - Preserving column order when
rowsmight be empty: Passingcolumns=["name", "age", "city"]alongsidepd.DataFrame(rows, columns=...)guarantees the resulting DataFrame still has the expected column headers even ifrowsends up empty ([]).
Comparison of DataFrame Population Methods
| Method | Time Complexity | Pandas 2.0+ Compatible? | Preserves dtypes? |
Best Used When |
|---|---|---|---|---|
pd.DataFrame(rows_list) |
$O(n)$ (single allocation) | Yes | Yes (inferred cleanly) | Building a DataFrame dynamically inside a loop or stream. |
df.loc[len(df)] = [...] |
$O(n^2)$ if repeated | Yes | Only if dtypes set upfront |
Adding a few individual rows to an existing DataFrame. |
pd.concat([df, new_df]) |
$O(n^2)$ if repeated in loop | Yes | Yes (if non-empty) | Combining existing DataFrames or batch chunks in one step. |
df.append() |
Removed | No (AttributeError) |
N/A | Deprecated in 1.4 and removed in Pandas 2.0—do not use. |
You must log in or register to comment.
