There's no great batteries-included way to do that (that I'm aware of). You could try to do it with the builtin containers, maybe something like:

data = [(some, headers, go, here),
        (data, from, first, row),
        (data, from, second, row),
        ... ,
        (data, from, last, row)]

and then build a custom key to sort it, like:

import operator

data = data[0] + sorted(data[1:],key=operator.itemgetter(col_num_to_sort_by))

But that's kind of ugly. It may be more maintainable to create a custom class that handles all that itself.

import operator

class Table(list): # inherits from list since it's just a list of lists
    def __init__(self, headers, rows_of_data):
        self.maxcellwidth = 0
        self.headers = headers
        for cell in self.headers:
            self.maxcellwidth = max(len(str(cell)), self.maxcellwidth)
        for row in rows_of_data:
            self.append(row)
            for cell in row:
                self.maxcellwidth = max(len(str(cell)), self.maxcellwidth)
    def sort_by_column(self, sort_by):
        """Sort by column and return a new Table"""
        return Table(self.headers, sorted(self, key=operator.itemgetter(sort_by)))
    def sort_by_columnip(self, sort_by):
        """Sort by column in-place"""
        self.sort(key=operator.itemgetter(sort_by))
    def __str__(self):
        return_value = list()
        header = "|".join(["{0:{1}}".format(header,self.maxcellwidth) for header in self.headers])
        return_value.append(header)
        return_value.append("-" * len(header))
        for row in self:
            return_value.append("|".join(["{0:{1}}".format(cell,self.maxcellwidth) for cell in row]))
        return "\n".join(return_value)

# TEST
>>> headers = ("one","two","three","four")
>>> data = [('1','2','3','5'), ('5','6','7','4')]
>>> table = Table(headers, data)
>>> print(table)
one  |two  |three|four 
-----------------------
1    |2    |3    |5    
5    |6    |7    |4 
>>> table.sort_by_columnip(3)
>>> print(table)
one  |two  |three|four 
-----------------------
5    |6    |7    |4    
1    |2    |3    |5  
Answer from Adam Smith on Stack Overflow
🌐
Pandas
pandas.pydata.org β€Ί docs β€Ί reference β€Ί api β€Ί pandas.DataFrame.sort_values.html
pandas.DataFrame.sort_values β€” pandas 3.0.2 documentation
>>> df.sort_values(by=["col1"]) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 5 C 4 3 F 4 D 7 2 e 3 NaN 8 4 D ... You can also provide multiple columns to by argument, as shown below.
🌐
Real Python
realpython.com β€Ί pandas-sort-python
pandas Sort: Your Guide to Sorting Data in Python – Real Python
June 13, 2023 - In this tutorial, you'll learn how to sort data in a pandas DataFrame using the pandas sort functions sort_values() and sort_index(). You'll learn how to sort by one or more columns and by index in ascending or descending order.
Discussions

pandas - How to sort Table in Python - Stack Overflow
Hello I would like to sort the Bundesliga table according to the points of each team not by the team name. Can someone help me? Currently I can sort the issue only by team name. I don't know how to... More on stackoverflow.com
🌐 stackoverflow.com
September 28, 2018
sorting - In Python, how can I store table and sort it based on one column? - Stack Overflow
The source data in table is out of order, but I would like to print out all this information in sorted order by ID. What sort of data structure do I keep these values in (different list for each column?) and how can I sort the remaining 3 columns based on ID? ... You might want to use a list of lists. For sorting see: wiki.python... More on stackoverflow.com
🌐 stackoverflow.com
sorting - How to sort a table of data in python? - Stack Overflow
To plot this properly in python (with imshow at matplotlib) I need to sort the content as following: 1 1 ? 1 2 ? 1 3 ? 2 1 ? 2 2 ? 2 3 ? 3 1 ? 3 2 ? 3 3 ? question mark is the related values for the third column. In another hand, if somebody knows about how to use imshow to plot unsorted data tables that would be helpful too. Think about the following data table as a 3x3 table coordinated by ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to sort pandas dataframe by one column - Stack Overflow
I have a dataframe like this: 0 1 2 0 354.7 April 4.0 1 55.4 August 8.0 2 176.5 December 12.0 3 95.5 February 2.0 4 85.6 January 1.0 5 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
SaltyCrane
saltycrane.com β€Ί blog β€Ί 2007 β€Ί 12 β€Ί how-to-sort-table-by-columns-in-python
How to sort a table by columns in Python - SaltyCrane Blog
December 5, 2007 - (1,0) would sort by column 1, then by column 0 """ for col in reversed(cols): table = sorted(table, key=operator.itemgetter(col)) return table if __name__ == '__main__': mytable = ( ('Joe', 'Clark', '1989'), ('Charlie', 'Babbitt', '1988'), ('Frank', 'Abagnale', '2002'), ('Bill', 'Clark', '2009'), ('Alan', 'Clark', '1804'), ) for row in sort_table(mytable, (1,0)): print row Results: ('Frank', 'Abagnale', '2002') ('Charlie', 'Babbitt', '1988') ('Alan', 'Clark', '1804') ('Bill', 'Clark', '2009') ('Joe', 'Clark', '1989') An example using Python's groupby and defaultdict to do the same task β€” posted 2014-10-09 ... Python data object motivated by a desire for a mutable namedtuple with default values β€” posted 2012-08-03
🌐
Data8
data8.org β€Ί datascience β€Ί _autosummary β€Ί datascience.tables.Table.sort.html
datascience.tables.Table.sort β€” datascience 0.18.1 documentation
>>> marbles = Table().with_columns( ... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"), ... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"), ... "Amount", make_array(4, 6, 12, 7, 9, 2), ... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00)) >>> marbles Color | Shape | Amount | Price Red | Round | 4 | 1.3 Green | Rectangular | 6 | 1.3 Blue | Rectangular | 12 | 2 Red | Round | 7 | 1.75 Green | Rectangular | 9 | 1.4 Green | Round | 2 | 1 >>> marbles.sort("Amount") Color | Shape | Amount | Price Green | Round | 2 | 1 Red | Rou
🌐
Python Forum
python-forum.io β€Ί thread-7450.html
How do you sort a table by one column?? (of floats)
Been struggling all day to figure this out, every guide online only shows how to use the sorted() function to change a table by a column alphabetically, there is no help anywhere if you are trying to sort by floats. **wall** #!/usr/bin/python imp...
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 52555225 β€Ί how-to-sort-table-in-python
pandas - How to sort Table in Python - Stack Overflow
September 28, 2018 - The file is already loaded into your python script. The columns are based off of http://www.football-data.co.uk/notes.txt Β· Assumes no errors in the HomeTeam column. The function below should be repeatable as long as your dataframe follows the same structure as the link you listed. import pandas as pd def sortTable(df): """ Returns a pd.DataFrame with goals scored by teams, sorted by total goals.
Top answer
1 of 1
2

There's no great batteries-included way to do that (that I'm aware of). You could try to do it with the builtin containers, maybe something like:

data = [(some, headers, go, here),
        (data, from, first, row),
        (data, from, second, row),
        ... ,
        (data, from, last, row)]

and then build a custom key to sort it, like:

import operator

data = data[0] + sorted(data[1:],key=operator.itemgetter(col_num_to_sort_by))

But that's kind of ugly. It may be more maintainable to create a custom class that handles all that itself.

import operator

class Table(list): # inherits from list since it's just a list of lists
    def __init__(self, headers, rows_of_data):
        self.maxcellwidth = 0
        self.headers = headers
        for cell in self.headers:
            self.maxcellwidth = max(len(str(cell)), self.maxcellwidth)
        for row in rows_of_data:
            self.append(row)
            for cell in row:
                self.maxcellwidth = max(len(str(cell)), self.maxcellwidth)
    def sort_by_column(self, sort_by):
        """Sort by column and return a new Table"""
        return Table(self.headers, sorted(self, key=operator.itemgetter(sort_by)))
    def sort_by_columnip(self, sort_by):
        """Sort by column in-place"""
        self.sort(key=operator.itemgetter(sort_by))
    def __str__(self):
        return_value = list()
        header = "|".join(["{0:{1}}".format(header,self.maxcellwidth) for header in self.headers])
        return_value.append(header)
        return_value.append("-" * len(header))
        for row in self:
            return_value.append("|".join(["{0:{1}}".format(cell,self.maxcellwidth) for cell in row]))
        return "\n".join(return_value)

# TEST
>>> headers = ("one","two","three","four")
>>> data = [('1','2','3','5'), ('5','6','7','4')]
>>> table = Table(headers, data)
>>> print(table)
one  |two  |three|four 
-----------------------
1    |2    |3    |5    
5    |6    |7    |4 
>>> table.sort_by_columnip(3)
>>> print(table)
one  |two  |three|four 
-----------------------
5    |6    |7    |4    
1    |2    |3    |5  
Find elsewhere
🌐
DataCamp
campus.datacamp.com β€Ί courses β€Ί data-manipulation-with-pandas β€Ί transforming-dataframes
Sorting rows | Python
Finding interesting bits of data in a DataFrame is often easier if you change the order of the rows. You can sort the rows by passing a column name to .sort_values().
🌐
Built In
builtin.com β€Ί data-science β€Ί data-frame-sorting-pandas
Sorting Data Frames in Pandas: A Hands-On Guide | Built In
Sorting by column names. Performing operations in place. Handling missing values. Apply the key function to the values before sorting. Python Pandas Tutorial (Part 7): Sorting Data.
🌐
Saturn Cloud
saturncloud.io β€Ί blog β€Ί how-to-sort-pandas-dataframe-from-one-column
How to Sort Pandas DataFrame by One or Multiple Column | Saturn Cloud Blog
November 9, 2023 - Sorting a Pandas DataFrame from one column can be done using the sort_values() method. The sort_values() method sorts the DataFrame based on the values of one or more columns. Suppose we have a DataFrame df with the following data: To sort the ...
🌐
MakeUseOf
makeuseof.com β€Ί home β€Ί programming β€Ί 5 essential ways to sort dataframes in python
5 Essential Ways to Sort DataFrames in Python
July 27, 2022 - Python sorts the data in ascending order by default. If you want to change the sorting order, you must explicitly mention it in your code. ... Set the ascending parameter to False to sort your column in descending order.
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί howto β€Ί sorting.html
Sorting Techniques β€” Python 3.14.4 documentation
February 23, 2026 - This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
🌐
H2O LLM Studio
docs.h2o.ai β€Ί h2o β€Ί latest-stable β€Ί h2o-docs β€Ί data-munging β€Ί sortcolumn.html
Sort columns β€” H2O 3.46.0.10 documentation
June 21, 2024 - Use the sort function in Python or the arrange function in R to create a new frame that is sorted by column(s) in ascending (default) or descending order.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί how-to-sort-pandas-dataframe
How to Sort Pandas DataFrame? - GeeksforGeeks
To immediately understand how sorting works, let’s look at a simple example: To sort a DataFrame by a single column, you use the sort_values() method and specify the column name using the by parameter.
Published Β  December 2, 2024
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί sort-rows-or-columns-in-pandas-dataframe-based-on-values
Sort Rows or Columns in Pandas Dataframe Based on Values - GeeksforGeeks
March 21, 2025 - It retrieves column names, sorts them using sorted() with a lambda function that calculates column sums and then reorders the DataFrame accordingly. ... In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 72174769 β€Ί how-to-sort-a-table-based-on-a-specific-column-both-scending-and-descending-in
how to sort a table based on a specific column (both scending and descending) in python - Stack Overflow
use sorted() if you want to sort data in descending order, just add reverse=True in sorted function but it allows you to sort only one column at a time. from prettytable import from_csv import csv, operator with open('test.txt', 'r') as open_file: ...
🌐
Trymito
trymito.io β€Ί excel-to-python β€Ί transformations β€Ί Sort
Excel to Python: Sort - A Complete Guide | Mito
# Sort in ascending order with NaN values at the end df.sort_values(by='Column1', na_position='last') ... Get answers from your data, not syntax errors. Download the Mito AI analyst ... Mito is the easiest way to write Excel formulas in Python.