How to change the order of DataFrame columns?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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:
This is the most common and readable approach.
Method 2: Using reindex()
reindex() also handles missing columns by filling with NaN:
Method 3: Move Specific Columns to Front
A reusable function:
Method 4: Using insert() to Place a Column
insert() adds a column at a specific position (modifies the DataFrame in place):
Method 5: Sort Columns Alphabetically
Method 6: Custom Sort with a Key Function
Method 7: Select by Data Type
Reorder by grouping numeric and non-numeric columns:
Method 8: Reverse Column Order
Dynamic Reordering Examples
Move a Column to the End
Swap Two Columns
Reorder Based on a Reference List
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):
Common Pitfalls
- KeyError on missing columns:
df[['col1', 'col2', 'missing']]raisesKeyErrorif'missing'does not exist. Usereindex()to handle missing columns gracefully (fills with NaN), or filter the list first. - Modifying vs creating: Most methods return a new DataFrame. Only
insert()andpop()modify in place. Assign the result back todffor 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 orswaplevel()andsort_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

