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 = ''
df = pd.read_csv(url)

To make things much easier let’s rename the columns with A, B and C.

df.columns = ['B', 'A', 'C']

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