pandas
data manipulation
column sorting
Python
data analysis

Sorting columns in pandas dataframe based on column name

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

Sorting pandas columns by column name is simple once you remember that columns are just an index on axis 1. The main question is not whether pandas can do it, but what kind of ordering you want: alphabetical, reverse alphabetical, or a custom business order. Pandas supports all of those, but the cleanest method depends on the case.

Sort Columns Alphabetically

The simplest built-in method is sort_index on axis 1.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "z_score": [1, 2],
6        "age": [30, 40],
7        "name": ["Ana", "Ben"],
8    }
9)
10
11sorted_df = df.sort_index(axis=1)
12print(sorted_df)

This sorts the column labels in ascending lexical order.

Equivalent result using reindex:

python
sorted_df = df.reindex(sorted(df.columns), axis=1)
print(sorted_df)

Both are fine. sort_index(axis=1) is usually the clearest when the goal is plain label sorting.

Reverse the Sort Order

If you want descending order:

python
sorted_desc = df.sort_index(axis=1, ascending=False)
print(sorted_desc)

This is useful for quick inspection, though business-oriented reporting usually prefers an explicit custom order instead of reverse alphabetical sorting.

Apply a Custom Column Order

Often the real requirement is not alphabetical order. It is "put these important columns first."

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "z_score": [1, 2],
6        "age": [30, 40],
7        "name": ["Ana", "Ben"],
8        "id": [101, 102],
9    }
10)
11
12order = ["id", "name", "age", "z_score"]
13reordered = df[order]
14print(reordered)

This is better than sorting when the desired sequence is domain-driven rather than lexical.

Sort by a Derived Key

Sometimes column names contain numbers or prefixes and normal string sorting is not what you want.

Example problem:

  • 'col1'
  • 'col10'
  • 'col2'

Lexical sorting puts col10 before col2. If you want natural numeric ordering, sort with a custom key.

python
1import pandas as pd
2import re
3
4df = pd.DataFrame(
5    {
6        "col10": [1, 2],
7        "col2": [3, 4],
8        "col1": [5, 6],
9    }
10)
11
12def numeric_key(name: str) -> int:
13    match = re.search(r"\d+", name)
14    return int(match.group()) if match else -1
15
16ordered_columns = sorted(df.columns, key=numeric_key)
17result = df[ordered_columns]
18print(result)

That gives col1, col2, col10, which is often what users expect.

Sort Only a Subset of Columns First

Another useful pattern is "bring some columns to the front and sort the rest automatically."

python
1priority = ["id", "name"]
2remaining = sorted([c for c in df.columns if c not in priority])
3result = df[priority + remaining]
4print(result)

This is a good compromise for data export workflows where a few columns are important and the rest can be alphabetized.

MultiIndex Columns Need Special Handling

If your DataFrame has MultiIndex columns, sort_index(axis=1) still works, but the sort operates on tuple-like labels. That is sometimes correct and sometimes surprising.

In that case, inspect df.columns first and decide whether you want:

  • full tuple sorting
  • sorting by one level only
  • a manually defined order

The method is the same, but the intent needs to be explicit.

Common Pitfalls

  • Using plain string sorting when column names contain numbers such as col1, col2, and col10.
  • Reordering with a manual list and forgetting one required column.
  • Assuming alphabetical order is the same as business-friendly order.
  • Forgetting that columns are axis 1, not axis 0.
  • Applying sort_values when the goal was to sort column labels rather than row data.

Summary

  • Use df.sort_index(axis=1) for simple alphabetical column sorting.
  • Use ascending=False for reverse order.
  • Use a manual list when the required order is business-driven.
  • Use a custom key when column names contain embedded numbers or patterns.
  • Keep in mind that sorting columns means working on axis 1, not sorting row values.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the 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.