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: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn
***To download the US Population By Cities 2018 csv file: ***
https://drive.google.com/uc?export=download&id=16oAd_l4M0YeiNThJcjZv10DGlO-ZCtmK
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)