In this tutorial, I will be showing you how to do a custom sorting with pandas dataframe.

Buy Me a Coffee? Your support is much appreciated!
PayPal Me:
Venmo: @Jie-Jenn

***To download the US Population By Cities 2018 csv file: ***

Source Code:

import pandas as pd

df = pd.read_csv('US Population By Cities 2018.csv')

mapping = {
    'New York': 0, 'California': 1, 'Texas': 2, 'Illinois': 3, 'Arizona': 4

df['sorting'] = df['state'].apply(lambda state_name: mapping[state_name])
df2 = df.sort_values(by=['sorting', 'city'], axis=0)