Pandas – How to change the order of columns in pandas.

Spread the love

Problem –

You have a pandas dataframe and you do not like the ordering of the columns. You want to change the orders of the columns.

Solution –

Let’s first read a dataset to work with.

df = pd.read_csv("")

Let’s say that you want rearrange the Gender, Marital Status and Age columns after the Type of Customer columns instead of at last.

To change the order of the columns, first you need to get the name of the columns.

# get column names
cols = df.columns.tolist()

Now, you need to rearrange the column names the way you like it.

cols = cols[:2] + cols[5:] + cols[2:5]

Now, all you have to do is select the data from the dataframe based on this rearranged column names and assign it back to the dataframe like shown below.

# rearrange the column names
df = df[cols]

If you want you can also manually rearrange the column names instead of list slicing method that we used. It completely up to you. The goal is to rearrange the column names the way you want it.

Rating: 1 out of 5.

Leave a Reply