Assign a scalar value directly to a new column name—such as df["new_col"] = np.nan (or pd.NA for nullable dtypes) for missing values, or df["new_col"] = 0 / df["new_col"] = "" for a constant default—to broadcast that value across every row in $O(1)$ C-vectorized time, or use df = df.assign(new_col=np.nan) when you want a non-mutating copy inside method chains.
Basic Example
import numpy as np
import pandas as pd
df = pd.DataFrame({
"user": ["Alice", "Bob", "Charlie"],
"score": [88, 92, 79],
})
# 1. Recommended (in-place): Add an empty float NaN column
df["notes_num"] = np.nan
# 2. Recommended (in-place): Add an empty nullable string column or constant default
df["tag"] = pd.Series(pd.NA, index=df.index, dtype="string")
df["retries"] = 0
print(df)
# Output:
# user score notes_num tag retries
# 0 Alice 88 NaN <NA> 0
# 1 Bob 92 NaN <NA> 0
# 2 Charlie 79 NaN <NA> 0
# 3. Non-mutating method chaining with `.assign()`:
df_extended = df.assign(status="pending", discount=np.nan)
Key Details & Edge Cases
- Choose the right dtype for your empty
NaNcolumn upfront (float64vs. nullable"Int64"/"string"):- Assigning
df["col"] = np.nancreates afloat64column. If you later assign strings into that column in Pandas 2.x+, you will trigger aFutureWarningorTypeErrorfor incompatible dtype assignment. - Pre-assign the intended nullable dtype when the column will later hold integers, booleans, or text:
- Text:
df["text_col"] = pd.Series(pd.NA, index=df.index, dtype="string") - Nullable integers:
df["int_col"] = pd.Series(pd.NA, index=df.index, dtype="Int64") - Datetime:
df["created_at"] = pd.NaT(createsdatetime64[ns])
- Text:
- Assigning
- Avoid
df["col"] = Nonefor numeric/boolean columns:- Assigning
Nonecreates anobjectdtype column (slow, non-vectorized), whereasnp.nancreatesfloat64andpd.NAwith an explicit nullable dtype ("Int64","boolean","string") preserves fast typed storage.
- Assigning
- Inserting the new column at a specific position (
df.insert()):- Standard
df["col"] = ...always appends the column to the rightmost end. To place it at a specific integer index (e.g., position1), usedf.insert(1, "new_col", np.nan)(mutatesdfin-place; raisesValueErrorif"new_col"already exists unlessallow_duplicates=True).
- Standard
- Adding multiple empty columns at once (
df.reindex()):- To add several missing columns simultaneously with a shared fill value without triggering
PerformanceWarning: DataFrame is highly fragmented, expand the column index with.reindex():new_cols = ["col_a", "col_b", "col_c"] df = df.reindex(columns=[*df.columns, *new_cols], fill_value=np.nan)
- To add several missing columns simultaneously with a shared fill value without triggering
- Never assign a mutable list or dict directly (
df["items"] = []):- Assigning
df["items"] = []either raisesValueError: Length of values (0) does not match length of indexor, iflen(df) == 1, shares a single list reference. Initialize object/list cells per row via[[] for _ in range(len(df))]only if nested lists are strictly needed.
- Assigning
Comparison of Methods for Adding an Empty or Default Column in Pandas
| Method | Mutates In-Place or Returns Copy? | Controls Column Position? | Best Used When |
|---|---|---|---|
df["col"] = np.nan (or scalar default) (Recommended) |
In-place | No (appends at end) | Standard single-column addition with np.nan, pd.NaT, 0, False, or "". |
df["col"] = pd.Series(pd.NA, index=df.index, dtype="string") |
In-place | No (appends at end) | Pre-allocating an empty column with strict nullable "string", "Int64", or "boolean" dtype. |
df = df.assign(col1=np.nan, col2="default") |
Returns new copy | No (appends at end) | Adding one or more columns cleanly inside a functional .pipe() / method chain. |
df.insert(loc, "col", np.nan) |
In-place | Yes (loc=0 for first column) |
Placing the new empty/default column at an exact positional index rather than the end. |
df.reindex(columns=[*df.columns, *new_cols], fill_value=np.nan) |
Returns new copy | Yes (arbitrary column order) | Adding dozens of empty columns at once without DataFrame block fragmentation. |
You must log in or register to comment.
