Skip to main content
v2026.11,986 entries · CC-BY 4.0

pandas select columns: loc, iloc & Methods Guide

A complete guide to pandas column selection: bracket syntax, .loc and .iloc indexing, data type filtering, Copy-on-Write behavior, and troubleshooting.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

When working with tabular empirical datasets, selecting specific subsets of variables is one of the most frequent operations in scientific programming. In Python, the pandas select columns workflow allows data analysts and researchers to isolate demographic indicators, clinical biomarkers, experimental conditions, or survey responses for downstream statistical modeling. Whether you need to extract a single variable or isolate dozens of measurements across longitudinal waves, knowing how to select columns in pandas efficiently prevents common data processing errors, minimizes memory overhead, and guarantees reproducible results.

What it is used for in research

In quantitative empirical research, raw data tables regularly contain hundreds of columns—including administrative timestamps, internal database keys, raw instrument telemetry, and auxiliary notes—that are extraneous to a given statistical hypothesis. The primary purpose of column selection in research pipelines is variable isolation, feature engineering, and data cleaning. Analysts use column filtering to separate predictor variables from outcome measures, isolate specific waves in longitudinal panel studies, subset demographic strata, and convert raw data tables into tidy analytical formats.

Column selection in pandas supports several distinct paradigms depending on research requirements:

  • Variable Subsetting: Isolating specific questionnaire batteries or physical measurements from multi-instrument survey datasets before passing them to regression or machine learning models.
  • Data Type Segregation: Partitioning numeric measurement scales from categorical factors or text notes using type-aware selectors like select_dtypes(), integrating directly with pandas dtypes inspection workflows.
  • Memory Optimization: Trimming high-dimensional datasets during or immediately after ingestion to ensure memory-constrained research environments (such as high-performance computing nodes or cloud containers) remain performant.
  • Pipeline Transformations: Feeding clean subsets into subsequent operations such as column renaming, feature combination using pandas add column methods, or conditional masking via pandas where.

How to install or access it

pandas is distributed as an open-source software package under the permissive BSD 3-Clause License. It requires Python 3.10 or newer for modern releases (pandas 2.2+ and 3.0). Researchers can install and access pandas through either PyPI or Conda-Forge, the two official package distribution ecosystems for scientific Python.

To install pandas via pip in a standard Python virtual environment, execute the following command in your terminal:

pip install pandas

For scientific computing environments managed through Anaconda or Miniconda, install pandas from the community-maintained conda-forge channel to guarantee compatible binary dependencies (such as BLAS and NumPy):

conda install -c conda-forge pandas

Once installed, verify the installation and import pandas alongside NumPy in your Python scripts or Jupyter notebooks:

import pandas as pd
import numpy as np

print(pd.__version__)

Step-by-step task

This step-by-step task walks through selecting columns from an empirical dataset using brackets, label-based indexing (.loc), integer-position indexing (.iloc), data type selection (select_dtypes), pattern matching (filter), and memory-efficient ingestion.

1. Create or load the research sample DataFrame

Consider an observational clinical study with patient identifiers, demographic information, treatment cohorts, and longitudinal biomarker measurements:

import pandas as pd
import numpy as np

# Sample clinical cohort dataset
data = {
    'patient_id': ['PT-101', 'PT-102', 'PT-103', 'PT-104'],
    'age': [45, 52, 38, 61],
    'cohort': ['Treatment_A', 'Control', 'Treatment_B', 'Treatment_A'],
    'baseline_crp': [2.4, 5.1, 1.8, 4.3],
    'followup_crp': [1.9, 5.3, 1.2, 3.8],
    'consent_signed': [True, True, True, False]
}

df = pd.DataFrame(data)
print(df)

2. Select a single column using bracket notation

To extract one variable as a 1D pandas Series, supply the column name as a string inside single square brackets:

# Returns a pandas Series
age_series = df['age']
print(type(age_series))
print(age_series)

If you prefer the output to remain a 2D DataFrame with a single column, wrap the column name inside a Python list (double brackets):

# Returns a single-column DataFrame
age_df = df[['age']]
print(type(age_df))
print(age_df)

3. Select multiple columns by label

To extract multiple specific variables, pass a list of column label strings inside square brackets:

# Select primary outcomes and identifiers
outcomes = df[['patient_id', 'baseline_crp', 'followup_crp']]
print(outcomes)

4. Select columns using label-based indexing with .loc

The .loc accessor provides explicit two-dimensional label-based indexing with the syntax df.loc[row_indexer, column_indexer]. To select all rows and specific columns, use a colon : for rows:

# Select columns by explicit list using .loc
subset_loc = df.loc[:, ['patient_id', 'cohort']]

# Select a contiguous range of columns by label slice
# Note: In .loc slicing, BOTH start and end labels are inclusive
biomarker_range = df.loc[:, 'baseline_crp':'followup_crp']
print(biomarker_range)

5. Select columns by integer position using .iloc

When column positions are known or fixed by schema index, use .iloc for 0-based positional indexing. Unlike .loc, slicing with .iloc follows standard Python half-open interval conventions (the start index is inclusive, but the stop index is exclusive):

# Select columns at index positions 0 and 2 (patient_id and cohort)
subset_pos = df.iloc[:, [0, 2]]

# Select columns from index 1 up to (excluding) index 4 (age, cohort, baseline_crp)
slice_pos = df.iloc[:, 1:4]
print(slice_pos)

6. Select columns dynamically by data type using select_dtypes

In quantitative studies, calculating summary statistics across all continuous variables requires isolating numerical features. The select_dtypes() method accepts types to include or exclude:

# Select all numeric variables (integers and floats)
numeric_vars = df.select_dtypes(include=['number'])
print(numeric_vars)

# Select all non-numeric variables (strings/objects and booleans)
non_numeric_vars = df.select_dtypes(exclude=['number'])
print(non_numeric_vars)

7. Filter columns by string pattern or regular expression

For large survey batteries or multi-wave panel studies where variable names share standardized naming prefixes or suffixes, the DataFrame.filter() method allows matching column names without manual typing:

# Select columns containing the substring 'crp'
crp_cols = df.filter(like='crp')

# Select columns matching a regular expression pattern
id_or_crp = df.filter(regex=r'^(patient|.*_crp$)')
print(id_or_crp)

When filtering categorical variables or missing records across these selected subsets, combine column selection with pandas isin and dropna in pandas for complete data cleaning.

8. Optimize memory during file ingestion

When working with large tabular datasets on disk, avoiding loading unused columns into memory is far more efficient than subsetting post-hoc. Use the usecols parameter in pd.read_csv():

# Read only required variables directly from disk
df_subset = pd.read_csv(
    'clinical_trial_large.csv',
    usecols=['patient_id', 'age', 'baseline_crp']
)

Output and how to read it

When you select columns in pandas, the structure and metadata of the returned object depend directly on the syntax used. Understanding how to inspect and interpret the resulting object is essential for downstream statistical procedures.

The primary distinction lies between 1D Series and 2D DataFrame outputs:

  • Single Bracket (df['age']): Returns a pandas.core.series.Series. It possesses a single dtype (e.g., int64), an index corresponding to the DataFrame row index, and a name attribute matching the selected column. It has no column axis (shape is (N,)).
  • Double Brackets or Slicing (df[['age']], df.loc[:, ['age']]): Returns a pandas.core.frame.DataFrame. It retains a two-dimensional tabular structure (shape is (N, 1) or (N, M)), an explicit columns Index, and distinct data types per column accessible via df.dtypes.

The following table summarizes the behavior, return type, and endpoint rules for standard pandas column selection techniques:

Selection Method Example Syntax Return Type Boundary Rule Primary Use Case
Single Bracket df['col'] Series Exact single match Vector operations, Series methods, single-variable plotting
Double Brackets df[['col1', 'col2']] DataFrame List of exact labels Subsetting multiple variables, feeding tabular models
Label Indexer (.loc) df.loc[:, 'col1':'col3'] DataFrame Closed interval (inclusive of both ends) Simultaneous row/column filtering, label-based range slicing
Positional Indexer (.iloc) df.iloc[:, 0:3] DataFrame Half-open interval (stop index excluded) Selecting columns by numerical order or programmatic index offsets
Data Type Filter df.select_dtypes(include='number') DataFrame Exact dtype matching Automated numeric scaling, summary tables, encoding passes
Pattern Filter df.filter(like='crp') DataFrame Substring or regex match Subsetting wide survey batteries and longitudinal wave prefixes

Troubleshooting

Researchers commonly encounter several predictable exceptions and warnings when selecting columns in pandas. The diagnostic solutions below address the most frequent issues.

1. KeyError when selecting column names

A KeyError occurs when one or more requested column names do not match any entry in df.columns. This often stems from unseen leading or trailing whitespace, capitalization discrepancies, or hidden non-printable characters in raw data exports.

Remedy: Inspect all column names explicitly using df.columns.tolist(). Clean all column names by stripping surrounding whitespace before selecting:

# Diagnostic check
print(df.columns.tolist())

# Normalize column names by removing whitespace
df.columns = df.columns.str.strip()

2. SettingWithCopyWarning and Chained Assignment

In older pandas versions, chaining column selection with downstream modification (e.g., df[['age', 'cohort']]['age'] = 50) generated a SettingWithCopyWarning because pandas could not guarantee whether the modified object was an independent copy or a view into the original array. In pandas 2.x and 3.0 with Copy-on-Write (CoW) enabled, chained assignment raises a ChainedAssignmentError or leaves the original DataFrame unaffected.

Remedy: Always perform column modifications using single-indexer assignment via .loc, or explicitly instantiate a standalone copy using .copy():

# Incorrect (chained assignment):
# df[['age']]['age'] = 50

# Correct: Explicit label assignment on parent DataFrame
df.loc[:, 'age'] = 50

# Correct: Standalone decoupled analytical copy
cohort_subset = df[['patient_id', 'age']].copy()
cohort_subset['age'] = cohort_subset['age'] + 1

3. Off-by-one errors from slice boundaries (.loc vs .iloc)

Confusing label slicing with integer position slicing causes unintended columns to be included or dropped. Remember that df.loc[:, 'col_a':'col_c'] includes col_c, whereas df.iloc[:, 0:2] selects columns at indices 0 and 1, stopping before index 2.

4. AttributeError when using dot notation

While accessing columns via dot notation (e.g., df.age) is syntactically valid in simple interactive sessions, it fails whenever a column name contains spaces (e.g., df.patient id), begins with numbers, or collides with existing DataFrame methods or attributes (such as df.count, df.min, df.size, or df.shape).

Remedy: Always use standard bracket notation (df['patient id'] or df['count']) in production and scientific codebases.

5. ValueError in select_dtypes

Calling df.select_dtypes() without arguments raises ValueError: at least one of include or exclude must be specified. Ensure you provide at least one valid dtype string or type object in a list, such as include=['number'] or exclude=['object'].

Free alternatives

Depending on data scale, programming environment, and computational architecture, several open-source and free data manipulation frameworks provide alternative column selection syntaxes. The comparison table below highlights how pandas compares to other widely used research tools:

Tool / Package Ecosystem Column Selection Syntax Execution Model Key Advantages in Research
pandas Python df[['col1', 'col2']]
df.loc[:, 'c1':'c2']
In-memory, single-threaded eager execution Ubiquitous ecosystem support; seamless integration with NumPy, SciPy, and scikit-learn.
Polars Python / Rust df.select(['col1', 'col2'])
df.select(cs.numeric())
Multi-threaded, vectorized, lazy evaluation available Extreme performance on multi-core workstations; selector expressions (polars.selectors) simplify complex type matching.
dplyr (tidyverse) R df %>% select(col1, col2)
df %>% select(where(is.numeric))
In-memory tidy evaluation Rich selection helpers (starts_with(), everything(), all_of()); standard in epidemiological and social science research.
Base R R df[, c("col1", "col2")]
subset(df, select = c(col1, col2))
Built-in runtime, single-threaded Zero external dependencies; preserves reproducibility across base R installations without package version drift.
DuckDB SQL / Python / R SELECT col1, col2 FROM df
SELECT * EXCLUDE (col3) FROM df
Vectorized columnar SQL engine, out-of-core processing Processes tabular files larger than RAM directly from disk; native Parquet and CSV querying with zero data copying.

FAQ

How do I select multiple columns in pandas?

To select multiple columns in pandas, pass a Python list containing the column names inside square brackets: df[['column_one', 'column_two']]. Alternatively, use label-based indexing with df.loc[:, ['column_one', 'column_two']] or integer position indexing with df.iloc[:, [0, 1]].

What is the difference between df[‘col’] and df[[‘col’]]?

The single-bracket expression df['col'] extracts the column as a 1D pandas Series object with a 1D shape (N,). The double-bracket expression df[['col']] preserves the 2D tabular structure, returning a pandas DataFrame with a 2D shape (N, 1).

How does column slicing differ between .loc and .iloc?

In .loc[:, 'col_start':'col_end'], selection is label-based and the slice is closed, meaning both col_start and col_end are included in the output. In .iloc[:, start_idx:end_idx], selection is integer position-based and follows Python standard slicing, meaning start_idx is included while end_idx is excluded.

How do I select columns based on their data type?

Use the DataFrame.select_dtypes() method. For example, df.select_dtypes(include=['number']) returns all integer and floating-point columns, while df.select_dtypes(include=['category', 'object']) isolates qualitative and text fields.

Why should I avoid dot notation (df.col_name) in research scripts?

Dot notation fails when column names contain spaces, special characters, or numerals. Furthermore, if a column name matches a built-in DataFrame attribute or method (such as count, size, or shape), dot notation accesses the DataFrame method rather than the underlying column series, resulting in silent logical bugs.

How does Copy-on-Write (CoW) affect column selection in modern pandas?

Under Copy-on-Write (standard in pandas 3.0 and optional in pandas 2.x via pd.options.mode.copy_on_write = True), selecting a column subset returns a view with delayed copying. Attempting chained assignment on selected subsets will not alter the original DataFrame and raises an error or warning, preventing unintended side effects across research analysis pipelines.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about pandas select columns: loc, iloc & Methods Guide

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →