How do you copy selected columns from one Pandas DataFrame into a new DataFrame? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you copy selected columns from one Pandas DataFrame into a new DataFrame?

message-square
0

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 list of column names (df[["col_a"]]), even when selecting a single column:
    • Single brackets df["col_a"] return a 1D pd.Series, whereas double brackets df[["col_a"]].copy() return a 2D pd.DataFrame.
  • 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 where sub["a"] = 0 emits SettingWithCopyWarning or mutates df. 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.
  • Selecting columns dynamically when some requested columns might be missing (df.reindex vs. df.filter):
    • df[["a", "missing_col"]] raises KeyError: "['missing_col'] not in index".
    • If you want to keep only whichever columns from a candidate list actually exist without raising KeyError, use df.filter(items=candidate_cols).copy() (ignores missing names).
    • If you want every requested column present in the output (filling missing ones with NaN), use df.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() or df.filter(like="date").copy()
    • By dtype: df.select_dtypes(include=["number"]).copy() or df.select_dtypes(exclude=["object"]).copy()
  • 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 .loc call:
      high_earners = df.loc[df["salary"] > 115000, ["name", "salary"]].copy()
      

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.