Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to change the order of Pandas DataFrame columns?

I have this DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))
I add more column(s) by assignment:

df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?
by

2 Answers

kshitijrana14
You could do something like this:
df = df[['mean', '0', '1', '2', '3']]

You can get the list of columns with:
cols = list(df.columns.values)

The output will produce:
['0', '1', '2', '3', 'mean']

...which is then easy to rearrange manually before dropping it into the first function
sandhya6gczb
To move the column mean to first, You can use methods like deque() and rotate(). Let us see how?

from collections import deque

columns = deque(df.columns.tolist())
columns.rotate()

df = df[columns]

Login / Signup to Answer the Question.