How to Sort Columns in Pandas Based on Column Names?

Spread the love

Problem –

You want to sort columns in Pandas based on column names.

Solution –

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)

Rating: 1 out of 5.

Leave a Reply