You want to sort columns in Pandas based on column names.
Let’s read a dataset to illustrate it.
import pandas as pd url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/Restaurant.csv' df = pd.read_csv(url) df.head()
To make things much easier let’s rename the columns with A, B and C.
df.columns = ['B', 'A', 'C'] df.head()
Now, If I want to sort these columns alphabetically, I have to write.
df = df.reindex(sorted(df.columns), axis=1)