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('https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv')
df.head()

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()
cols

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]
df1

Or I can use list slicing like this.

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

df2 = df[new_cols]
df2

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'])
df3

Rating: 1 out of 5.

Leave a Reply