How to Change the Order of Columns in pandas dataframe

Spread the love

Problem –

You want to change the order of columns in pandas dataframe.

Solution –

Let’s read a dataset to illustrate this.

import pandas as pd

df = pd.read_csv('')

To change the order of columns in pandas you can do it manually or using list slicing. But first you have to get the column names. To do that we can use –

cols = df.columns.tolist()

Let’s say I want to move the Age column to first. I can so it manually like this.

cols_new = ['Age','Customer', 'Type of Customer','Items','Net Sales',
            'Method of Payment','Gender','Marital Status']

df1 = df[cols_new]

Or I can use list slicing like this.

new_cols = cols = cols[-1:] + cols[:-1]

df2 = df[new_cols]

Another method is using dataframe.reindex() method.

df3 = df.reindex(columns=['Age','Customer', 'Type of Customer','Items','Net Sales','Method of Payment','Gender','Marital Status'])

Rating: 1 out of 5.

Leave a Reply