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.
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
Related reading
- How to change the order of DataFrame columns?
- How to change the threshold on decision tree classifier model?
- How to change tick label font size
- How to check dataset if valid for some classify in WEKA api?
- How to check a string for specific characters?
- How to check Django version
- How to check dtype for all columns in a Pandas dataframe?
- How to check for NaN values
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.