Data Manipulation
Python Programming
Pandas Library
DataFrames
Coding Tutorial

How to change the order of DataFrame columns?

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

Reordering columns in a pandas DataFrame is a common operation when preparing data for display, export, or downstream processing. There are several approaches: direct column list selection, reindex(), inserting columns at specific positions, and sorting columns alphabetically. Each method creates a new DataFrame with columns in the desired order without modifying the underlying data.

Method 1: Direct Column List Selection

Pass a list of column names in the desired order:

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'name': ['Alice', 'Bob', 'Charlie'],
5    'age': [25, 30, 35],
6    'city': ['NYC', 'LA', 'Chicago'],
7    'salary': [70000, 80000, 90000]
8})
9
10# Reorder columns
11df = df[['city', 'name', 'age', 'salary']]
12print(df)
13#      city     name  age  salary
14# 0     NYC    Alice   25   70000
15# 1      LA      Bob   30   80000
16# 2 Chicago  Charlie   35   90000

This is the most common and readable approach.

Method 2: Using reindex()

python
df = df.reindex(columns=['salary', 'name', 'city', 'age'])

reindex() also handles missing columns by filling with NaN:

python
df = df.reindex(columns=['name', 'age', 'department', 'city'])
# 'department' column is added with NaN values

Method 3: Move Specific Columns to Front

python
# Move 'salary' to the first column
cols = ['salary'] + [c for c in df.columns if c != 'salary']
df = df[cols]

A reusable function:

python
1def move_columns_to_front(df, columns):
2    remaining = [c for c in df.columns if c not in columns]
3    return df[columns + remaining]
4
5df = move_columns_to_front(df, ['salary', 'name'])

Method 4: Using insert() to Place a Column

insert() adds a column at a specific position (modifies the DataFrame in place):

python
# Remove the column first, then insert at position 0
col = df.pop('salary')
df.insert(0, 'salary', col)
python
# Insert at position 2 (third column)
col = df.pop('city')
df.insert(2, 'city', col)

Method 5: Sort Columns Alphabetically

python
1# Ascending
2df = df[sorted(df.columns)]
3
4# Descending
5df = df[sorted(df.columns, reverse=True)]
6
7# Using sort_index on axis=1
8df = df.sort_index(axis=1)

Method 6: Custom Sort with a Key Function

python
1# Put columns starting with 'id' first, then alphabetical
2def column_sort_key(col):
3    if col.startswith('id'):
4        return (0, col)
5    return (1, col)
6
7df = df[sorted(df.columns, key=column_sort_key)]

Method 7: Select by Data Type

Reorder by grouping numeric and non-numeric columns:

python
1# Numeric columns first, then object columns
2numeric_cols = df.select_dtypes(include='number').columns.tolist()
3other_cols = df.select_dtypes(exclude='number').columns.tolist()
4df = df[numeric_cols + other_cols]

Method 8: Reverse Column Order

python
df = df[df.columns[::-1]]

Dynamic Reordering Examples

Move a Column to the End

python
col = 'name'
df = df[[c for c in df.columns if c != col] + [col]]

Swap Two Columns

python
1cols = list(df.columns)
2idx_a, idx_b = cols.index('name'), cols.index('city')
3cols[idx_a], cols[idx_b] = cols[idx_b], cols[idx_a]
4df = df[cols]

Reorder Based on a Reference List

python
1# Only reorder columns that exist, ignore missing ones
2desired_order = ['id', 'name', 'email', 'age', 'city', 'salary']
3actual = [c for c in desired_order if c in df.columns]
4remaining = [c for c in df.columns if c not in desired_order]
5df = df[actual + remaining]

Performance Comparison

All reordering methods are O(1) in terms of data copying — pandas internally adjusts column references without moving data in memory (until you actually access the data):

python
1import timeit
2
3# All methods are roughly equivalent in speed
4# Direct selection: ~50 μs for 100-column DataFrame
5# reindex(): ~60 μs
6# sort_index(axis=1): ~80 μs

Common Pitfalls

  • KeyError on missing columns: df[['col1', 'col2', 'missing']] raises KeyError if 'missing' does not exist. Use reindex() to handle missing columns gracefully (fills with NaN), or filter the list first.
  • Modifying vs creating: Most methods return a new DataFrame. Only insert() and pop() modify in place. Assign the result back to df for the other methods.
  • Losing columns: When reordering with a column list, any column not in the list is dropped. Double-check that your list includes all columns.
  • MultiIndex columns: For DataFrames with multi-level column indexes, use reindex() with tuples or swaplevel() and sort_index().
  • Chained indexing: df[cols] returns a copy. Subsequent modifications to the reordered DataFrame do not affect the original.

Summary

  • Use df[['col1', 'col2', ...]] for simple, explicit reordering
  • Use df.reindex(columns=[...]) when some columns might not exist
  • Use df.insert(pos, name, col) to place a column at a specific position in place
  • Use df[sorted(df.columns)] to sort columns alphabetically
  • Write helper functions for common patterns like moving columns to front or grouping by dtype

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.