python
pandas
dataframe
drop column
integer index

python dataframe pandas drop column using int

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Dropping a pandas column by integer position is a little trickier than it first appears because DataFrame.drop() works by label, not by positional index. The safe pattern is to map the integer position to the real column label first, then drop by that label.

Why a Plain Integer Can Mislead

This is the key distinction:

  • labels identify columns by name
  • positions identify columns by order

drop() uses labels. So if you write:

python
df.drop(columns=[1])

pandas treats 1 as a column label. That only works if the actual column name is 1.

Map Position to Label First

The safest direct pattern is:

python
1import pandas as pd
2
3df = pd.DataFrame({
4    "id": [1, 2, 3],
5    "name": ["A", "B", "C"],
6    "score": [90, 80, 70]
7})
8
9idx = 1
10col_name = df.columns[idx]
11result = df.drop(columns=[col_name])
12print(result)

This makes the label-versus-position step explicit and avoids accidental confusion.

Drop Multiple Columns by Position

For several positions, convert them all to labels:

python
1to_remove = [0, 2]
2labels = df.columns[to_remove]
3result = df.drop(columns=labels)
4print(result)

This is often simpler than trying to express the whole thing as one indirect indexing trick.

Keep Columns by Position with iloc

Sometimes it is clearer to build a keep-mask and select the remaining columns:

python
1import numpy as np
2
3remove_idx = 2
4mask = np.ones(df.shape[1], dtype=bool)
5mask[remove_idx] = False
6
7result = df.iloc[:, mask]
8print(result)

This is useful when the logic is fundamentally position-driven rather than label-driven.

A Small Helper Function

If your pipeline frequently drops by position, wrap the conversion and validation:

python
1from typing import Iterable
2
3def drop_by_index(frame: pd.DataFrame, indices: Iterable[int]) -> pd.DataFrame:
4    indices = list(indices)
5
6    for idx in indices:
7        if idx < 0 or idx >= frame.shape[1]:
8            raise IndexError(f"Column index out of range: {idx}")
9
10    labels = frame.columns[indices]
11    return frame.drop(columns=labels)
12
13print(drop_by_index(df, [1]))

This gives you one place for error handling and keeps ETL code cleaner.

Schema Drift Is the Real Risk

Position-based dropping is fragile when the source schema changes. If a provider inserts a new column at the front, position 1 may now mean something different.

That is why semantic names are usually better than positions. If you must use positions, validate the expected schema before transforming:

python
1expected = ["id", "name", "score"]
2if list(df.columns) != expected:
3    raise ValueError("Unexpected schema order")
4
5clean = drop_by_index(df, [1])
6print(clean)

Failing fast is much better than silently dropping the wrong column.

Numeric Column Labels Need Extra Care

Some DataFrames really do use integer labels:

python
1numeric_cols = pd.DataFrame({0: [1], 1: [2], 2: [3]})
2
3print(numeric_cols.drop(columns=[1]))                 # label-based
4print(numeric_cols.drop(columns=[numeric_cols.columns[1]]))  # position resolved to label

In that case, label and position can look identical even though they are conceptually different. Be explicit about which one you mean.

Common Pitfalls

  • Passing an integer directly to drop() and expecting positional behavior.
  • Forgetting to validate bounds before converting positions to labels.
  • Relying on column order in a pipeline where the upstream schema can drift.
  • Mixing label-based and position-based logic in one unclear line.
  • Forgetting that numeric labels and integer positions are not automatically the same thing.

Summary

  • 'drop() removes columns by label, not by position.'
  • Convert integer positions with df.columns[idx] before dropping.
  • Use iloc masks when the logic is more naturally expressed as "keep these positions."
  • Validate schema order if position-based dropping is unavoidable.
  • Prefer semantic column names when stability matters more than brevity.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.