Use new_df = df[["col_a", "col_b"]].copy() (or df.loc[:, ["col_a", "col_b"]].copy()) to extract a subset of columns as an independent DataFrame—always chaining .copy() so subsequent modifications to new_df never trigger Pandas’ SettingWithCopyWarning or silently mutate the original DataFrame via Copy-on-Write / shared buffer references.
Basic Example
import pandas as pd
df = pd.DataFrame({
"id": [101, 102, 103],
"name": ["Alice", "Bob", "Charlie"],
"department": ["Engineering", "Design", "Engineering"],
"salary": [125000, 110000, 132000],
})
# 1. Recommended: Double-bracket list selection + explicit `.copy()`
selected_cols = ["id", "name", "salary"]
new_df = df[selected_cols].copy()
# Modifying `new_df` is completely isolated from `df`:
new_df["salary"] = new_df["salary"] * 1.10
print(new_df)
# Output:
# id name salary
# 0 101 Alice 137500.0
# 1 102 Bob 121000.0
# 2 103 Charlie 145200.0
# 2. Pattern-based column selection with `.filter()` + `.copy()`:
numeric_or_id = df.filter(items=["id", "salary"]).copy()
Key Details & Edge Cases
- Always pass a
listof column names (df[["col_a"]]), even when selecting a single column:- Single brackets
df["col_a"]return a 1Dpd.Series, whereas double bracketsdf[["col_a"]].copy()return a 2Dpd.DataFrame.
- Single brackets
- Why
.copy()matters across Pandas 1.x, 2.x, and 3.x:- In Pandas 1.x / 2.x (without Copy-on-Write enabled),
sub = df[["a", "b"]]can return a view/reference wrapper wheresub["a"] = 0emitsSettingWithCopyWarningor mutatesdf. In Pandas 2.x with CoW / Pandas 3.0+,df[["a", "b"]]uses lazy Copy-on-Write, while.copy()makes ownership explicit across all Pandas versions.
- In Pandas 1.x / 2.x (without Copy-on-Write enabled),
- Selecting columns dynamically when some requested columns might be missing (
df.reindexvs.df.filter):df[["a", "missing_col"]]raisesKeyError: "['missing_col'] not in index".- If you want to keep only whichever columns from a candidate list actually exist without raising
KeyError, usedf.filter(items=candidate_cols).copy()(ignores missing names). - If you want every requested column present in the output (filling missing ones with
NaN), usedf.reindex(columns=candidate_cols).copy().
- Selecting columns by regex pattern, prefix/suffix, or data type (
filter/select_dtypes):- By regex or substring:
df.filter(regex=r"^metric_").copy()ordf.filter(like="date").copy() - By dtype:
df.select_dtypes(include=["number"]).copy()ordf.select_dtypes(exclude=["object"]).copy()
- By regex or substring:
- Copying columns and filtering rows simultaneously (
df.loc[row_mask, cols].copy()):- Instead of chained indexing (
df[df["salary"] > 115000][["name", "salary"]]), combine both axes in a single.loccall:high_earners = df.loc[df["salary"] > 115000, ["name", "salary"]].copy()
- Instead of chained indexing (
Comparison of Column-Selection & Copying Methods in Pandas
| Method | Missing Column Behavior | Supports Row Filtering in One Step? | Return Type | Best Used When |
|---|---|---|---|---|
df[["col1", "col2"]].copy() (Recommended) |
Raises KeyError (strict validation) |
No (columns only) | Independent pd.DataFrame |
Standard extraction of a known list of columns into a standalone DataFrame. |
df.loc[row_mask, ["col1", "col2"]].copy() |
Raises KeyError |
Yes (row_mask or :) |
Independent pd.DataFrame |
Extracting selected columns alongside a boolean row filter or index slice. |
df.filter(items=cols).copy() (or regex= / like=) |
Silently skips missing columns | No | Independent pd.DataFrame |
Dynamic schemas where optional columns may be absent or matched by naming pattern. |
df.reindex(columns=cols).copy() |
Adds missing columns filled with NaN |
No | Independent pd.DataFrame |
Enforcing an exact output column schema even when some columns are missing in input. |
df.select_dtypes(include=[...]).copy() |
N/A (matches by dtype) | No | Independent pd.DataFrame |
Selecting all numeric, datetime, or string columns for preprocessing or ML pipelines. |
You must log in or register to comment.
