Sorting arrays in NumPy by column
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In NumPy, "sort by column" can mean two different operations, and mixing them up is a common source of confusion. You might want to sort each column independently, or you might want to reorder entire rows based on the values in one specific column.
Sorting Each Column Independently
If you call np.sort with axis=0, NumPy sorts each column on its own:
Output:
This does not preserve the original row relationships. NumPy simply sorts column 0 by itself and column 1 by itself.
That is useful for column-wise statistics or normalization steps, but it is not what most people mean when they want to sort a table by a column.
Sorting Rows by One Column
If you want the rows to stay intact and be ordered by a given column, use argsort on that column and then index the full array:
Output:
In this example, a[:, 1] extracts the second column, argsort() returns the row order that would sort it, and a[order] applies that ordering to the full matrix.
Sort by a Different Column or Descending
Sorting by the first column is the same pattern:
For descending order, reverse the index order:
That gives you the rows ordered from the largest value in column 1 to the smallest.
Sort by Multiple Columns
When ties matter, use np.lexsort. It sorts using multiple keys, with the last key as the primary key.
Here the primary sort key is column 0, then column 1, then column 2.
This is the NumPy equivalent of an SQL ORDER BY with multiple columns.
Structured Arrays Are Another Option
If your data is truly tabular and columns have different meanings, a structured array can make named-column sorting easier:
This is handy when the columns represent fields rather than just numeric positions.
Common Pitfalls
The biggest pitfall is using np.sort(a, axis=0) when you actually want row-wise sorting by one column. That operation breaks row alignment.
Another common mistake is forgetting that argsort() returns indices, not the sorted data itself. You still need to apply those indices back to the array.
People also get tripped up by np.lexsort because the last key is the primary one. If the order looks backward, check the argument order carefully.
Finally, if the array contains mixed types or is really table-shaped business data, NumPy may not be the best tool. A pandas DataFrame can be easier to read and maintain for that kind of work.
Summary
- Use
np.sort(a, axis=0)only when you want each column sorted independently. - Use
a[a[:, col].argsort()]when you want to sort rows by a specific column. - Reverse the
argsortresult for descending order. - Use
np.lexsortfor stable multi-column ordering. - Make sure you are choosing between column-wise sorting and row-wise sorting intentionally.

