The below answer is an old answer. It still works. Anyhow, another very elegant solution has been posted below , using the key argument.


I just discovered that with pandas 15.1 it is possible to use categorical series (https://pandas.pydata.org/docs/user_guide/categorical.html)

As for your example, lets define the same data-frame and sorter:

import pandas as pd

data = {
    'id': [2967, 5335, 13950, 6141, 6169],
    'Player': ['Cedric Hunter', 'Maurice Baker', 
               'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'],
    'Year': [1991, 2004, 2001, 2009, 1997],
    'Age': [27, 25, 22, 34, 31],
    'Tm': ['CHH', 'VAN', 'TOT', 'OKC', 'DAL'],
    'G': [6, 7, 60, 52, 81]
}

# Create DataFrame
df = pd.DataFrame(data)

# Define the sorter
sorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL', 'DEN',
          'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL',
          'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI',
          'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN', 'WAS', 'WSB']

With the data-frame and sorter, which is a category-order, we can do the following in pandas 15.1:

# Convert Tm-column to category and in set the sorter as categories hierarchy
# You could also do both lines in one just appending the cat.set_categories()
df.Tm = df.Tm.astype("category")
df.Tm = df.Tm.cat.set_categories(sorter)

print(df.Tm)
Out[48]: 
0    CHH
1    VAN
2    TOT
3    OKC
4    DAL
Name: Tm, dtype: category
Categories (38, object): [TOT < ATL < BOS < BRK ... UTA < VAN < WAS < WSB]

df.sort_values(["Tm"])  ## 'sort' changed to 'sort_values'
Out[49]: 
   Age   G           Player   Tm  Year     id
2   22  60      Ratko Varda  TOT  2001  13950
0   27   6    Cedric Hunter  CHH  1991   2967
4   31  81  Adrian Caldwell  DAL  1997   6169
3   34  52       Ryan Bowen  OKC  2009   6141
1   25   7    Maurice Baker  VAN  2004   5335
Answer from dmeu on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.sort_values.html
pandas.DataFrame.sort_values — pandas 3.0.2 documentation
For DataFrames, this option is only applied when sorting on a single column or label. na_position{‘first’, ‘last’}, default ‘last’ · Puts NaNs at the beginning if first; last puts NaNs at the end. ... If True, the resulting axis will be labeled 0, 1, …, n - 1. ... Apply the key function to the values before sorting.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-pandas-dataframe-sort_values-set-1
Pandas Dataframe.sort_values() - GeeksforGeeks
November 29, 2024 - In Pandas, sort_values() function sorts a DataFrame by one or more columns in ascending or descending order.
Discussions

python - sorting by a custom list in pandas - Stack Overflow
Naturally, since you must construct your custom list with all possible values in your sort field, this is good mostly for categorical sorting and would not be suitable for continuous variables (unless the possible values are known up front) and columns with a very high cardinality. import pandas as ... More on stackoverflow.com
🌐 stackoverflow.com
python - Why does my Pandas DataFrame not display new order using `sort_values`? - Stack Overflow
I have a Pandas DataFrame of register transactions with shape like (500,4): Time datetime64[ns] Net Total float64 Tax float64 Total Due float64 · I'm working through my code in a Python3 Jupyter notebook. I can't get past sorting any column. Working through the different code examples for sort, I'm not seeing the output reorder when I inspect the df. So, I've reduced the problem to trying to order just one column: df.sort_values... More on stackoverflow.com
🌐 stackoverflow.com
Sort_values() doesn't work
I have calculated the “earn >50K countries”, and used “.sort_values(ascending=False)” to sort the highest value (Iran). However, it becomes Haiti, which is obviously not the highest value in the DataFrame. Can anyone please help me figure out why “sort_values()” doesn’t work in ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
October 1, 2022
[Pandas] What does "sort_values.index" do in this code?
It might be that seeing the value of some parts of the dataframe and groupby object will be clearer that any description. I would get on an interactive repl or jupyter and examine the subexpressions used and see how the data is being rearranged in each step: d.head() d.groupby('class')['survived'] d.groupby('class')'survived'].mean() d.groupby('class')'survived'].mean().sort_values() x m A lot of pandas operations can best be learned by doing trial and error in an interactive session; try everything out with variations, make errors to find the limits and to get used to the terminology used in tracebacks, experiment to solidify your understanding. More on reddit.com
🌐 r/learnpython
1
1
July 26, 2022
🌐
W3Schools
w3schools.com › python › pandas › ref_df_sort_values.asp
Pandas DataFrame sort_values() Method
import pandas as pd data = { "age": ... newdf = df.sort_values(by='age') Try it Yourself » · The sort_values() method sorts the DataFrame by the specified label....
🌐
Data Science Discovery
discovery.cs.illinois.edu › guides › Modifying-DataFrames › sorting-a-dataframe-with-pandas
Sorting a DataFrame Using Pandas - Data Science Discovery
The sort_values method of a DataFrame is used to sort a DataFrame by the data in a column. To explore sorting, we'll use a DataFrame of five cities, across three states, with various populations: import pandas as pd\n&nbsp;\n# Creates a DataFrame ...
🌐
Favtutor
favtutor.com › articles › pandas-sort-by-columnns-sort-values
Pandas DataFrame sort_values() | Sort by Column
December 1, 2023 - The sort_values() function in Pandas allows us to sort DataFrames on the basis of one or more columns.
🌐
KDnuggets
kdnuggets.com › advanced-pandas-patterns-most-data-scientists-dont-use
Advanced Pandas Patterns Most Data Scientists Don’t Use - KDnuggets
2 weeks ago - When pandas stores strings as object dtype, operations on those columns run in Python rather than C. For columns with low cardinality, such as status codes, region names, or categories, converting them to a categorical dtype can meaningfully speed up groupby and value_counts().
Find elsewhere
🌐
Statology
statology.org › home › pandas: how to sort dataframe based on string column
Pandas: How to Sort DataFrame Based on String Column
January 12, 2023 - import pandas as pd #sort rows based on strings in 'product' column df = df.sort_values('product') #view updated DataFrame print(df) product sales 7 A13 28 4 A2 14 2 A22 19 0 A3 18 1 A5 22 3 A50 14 5 A7 11 6 A9 20
🌐
Skytowner
skytowner.com › explore › pandas_dataframe_sort_values_method
Pandas DataFrame | sort_values method with Examples
Pandas DataFrame.sort_values(~) method sorts the source DataFrame either by column or row values.
🌐
Medium
medium.com › @whyamit101 › understanding-pandas-sort-values-with-basic-examples-e8e0f974d2c7
Understanding pandas.sort_values() with Basic Examples | by why amit | Medium
February 26, 2025 - It’s messy, filled with missing values, and sometimes you need to sort based on more than one condition. Let’s take it up a notch. ... Imagine you’ve got a guest list for an event. You want to sort the names by age first, but if two people have the same age, you’d like them sorted alphabetically. That’s where sorting by multiple columns comes into play. ... import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 25, 22]} df = pd.DataFrame(data) # Sorting by 'Age' (ascending) and then by 'Name' (descending) sorted_df = df.sort_values(by=['Age', 'Name'], ascending=[True, False]) print(sorted_df)
Top answer
1 of 9
136

The below answer is an old answer. It still works. Anyhow, another very elegant solution has been posted below , using the key argument.


I just discovered that with pandas 15.1 it is possible to use categorical series (https://pandas.pydata.org/docs/user_guide/categorical.html)

As for your example, lets define the same data-frame and sorter:

import pandas as pd

data = {
    'id': [2967, 5335, 13950, 6141, 6169],
    'Player': ['Cedric Hunter', 'Maurice Baker', 
               'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'],
    'Year': [1991, 2004, 2001, 2009, 1997],
    'Age': [27, 25, 22, 34, 31],
    'Tm': ['CHH', 'VAN', 'TOT', 'OKC', 'DAL'],
    'G': [6, 7, 60, 52, 81]
}

# Create DataFrame
df = pd.DataFrame(data)

# Define the sorter
sorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL', 'DEN',
          'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL',
          'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI',
          'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN', 'WAS', 'WSB']

With the data-frame and sorter, which is a category-order, we can do the following in pandas 15.1:

# Convert Tm-column to category and in set the sorter as categories hierarchy
# You could also do both lines in one just appending the cat.set_categories()
df.Tm = df.Tm.astype("category")
df.Tm = df.Tm.cat.set_categories(sorter)

print(df.Tm)
Out[48]: 
0    CHH
1    VAN
2    TOT
3    OKC
4    DAL
Name: Tm, dtype: category
Categories (38, object): [TOT < ATL < BOS < BRK ... UTA < VAN < WAS < WSB]

df.sort_values(["Tm"])  ## 'sort' changed to 'sort_values'
Out[49]: 
   Age   G           Player   Tm  Year     id
2   22  60      Ratko Varda  TOT  2001  13950
0   27   6    Cedric Hunter  CHH  1991   2967
4   31  81  Adrian Caldwell  DAL  1997   6169
3   34  52       Ryan Bowen  OKC  2009   6141
1   25   7    Maurice Baker  VAN  2004   5335
2 of 9
76

Below is an example that performs lexicographic sort on a dataframe. The idea is to create an numerical index based on the specific sort. Then to perform a numerical sort based on the index. A column is added to the dataframe to do so, and is then removed.

import pandas as pd

# Create DataFrame
df = pd.DataFrame(
{'id':[2967, 5335, 13950, 6141, 6169],
    'Player': ['Cedric Hunter', 'Maurice Baker',
               'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'],
    'Year': [1991, 2004, 2001, 2009, 1997],
    'Age': [27, 25, 22, 34, 31],
    'Tm': ['CHH' ,'VAN' ,'TOT' ,'OKC', 'DAL'],
    'G': [6, 7, 60, 52, 81]})

# Define the sorter
sorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL','DEN',
          'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL',
          'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI',
          'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN',
          'WAS', 'WSB']

# Create the dictionary that defines the order for sorting
sorterIndex = dict(zip(sorter, range(len(sorter))))

# Generate a rank column that will be used to sort
# the dataframe numerically
df['Tm_Rank'] = df['Tm'].map(sorterIndex)

# Here is the result asked with the lexicographic sort
# Result may be hard to analyze, so a second sorting is
# proposed next
## NOTE: 
## Newer versions of pandas use 'sort_values' instead of 'sort'
df.sort_values(['Player', 'Year', 'Tm_Rank'],
        ascending = [True, True, True], inplace = True)
df.drop('Tm_Rank', 1, inplace = True)
print(df)

# Here is an example where 'Tm' is sorted first, that will 
# give the first row of the DataFrame df to contain TOT as 'Tm'
df['Tm_Rank'] = df['Tm'].map(sorterIndex)
## NOTE: 
## Newer versions of pandas use 'sort_values' instead of 'sort'
df.sort_values(['Tm_Rank', 'Player', 'Year'],
        ascending = [True , True, True], inplace = True)
df.drop('Tm_Rank', 1, inplace = True)
print(df)
🌐
The Spectator
spectator.com › home › coffee house
Hungary has become a tired gerontocracy | The Spectator
4 weeks ago - Crime has ceased to be an issue, partly because the population is aging. The people, like pandas, do not breed. There is boredom and ennui. There is nothing analogous to, say, the killing of Iryna Zarutska. Hungary has had a dreadful century and is now a tired sort of place
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › sort_values
Python Pandas DataFrame sort_values() - Sort Data by Values | Vultr Docs
December 27, 2024 - This code sorts the DataFrame df by the 'Age' column in ascending order, which is the default sorting order in sort_values(). Use the ascending=False parameter to sort a DataFrame in descending order.
🌐
Kaggle
kaggle.com › code › mehakiftikhar › amazon-sales-dataset-eda
Amazon Sales Dataset EDA | Kaggle
September 28, 2025 - Explore and run machine learning code with Kaggle Notebooks | Using data from Amazon Sales Dataset
🌐
freeCodeCamp
freecodecamp.org › news › how-to-sort-values-in-pandas
pandas.DataFrame.sort_values - How To Sort Values in Pandas
March 13, 2023 - We saw two code examples on how to sort data in Pandas in ascending or descending order. You can use the sort_values() method's ascending parameter to sort data in ascending or descending order.
🌐
GeeksforGeeks
geeksforgeeks.org › python › sort-dataframe-according-to-row-frequency-in-pandas
Sort Dataframe according to row frequency in Pandas - GeeksforGeeks
July 23, 2025 - sort_values(): This method helps us to sort our dataframe. In this method, we pass the column and our data frame is sorted according to this column. Example 1: Program to sort data frame in descending order according to the element frequency.
🌐
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.
🌐
freeCodeCamp
forum.freecodecamp.org › python
Sort_values() doesn't work - Python - The freeCodeCamp Forum
October 1, 2022 - I have calculated the “earn >50K countries”, and used “.sort_values(ascending=False)” to sort the highest value (Iran). However, it becomes Haiti, which is obviously not the highest value in the DataFrame. Can anyone pl…