Reorder certain columns in pandas dataframe

Setup

cols = ['2','4','9','A','1','B','C']
df = pd.DataFrame(1, range(3), cols)

df

   2  4  9  A  1  B  C
0  1  1  1  1  1  1  1
1  1  1  1  1  1  1  1
2  1  1  1  1  1  1  1

sorted with key

key = lambda x: (x != 'A', x != 'B', x != 'C')
df[sorted(df, key=key)]

   A  B  C  2  4  9  1
0  1  1  1  1  1  1  1
1  1  1  1  1  1  1  1
2  1  1  1  1  1  1  1

Better suited for longer length of first column members

first_cols = ['A', 'B', 'C']
key = lambda x: tuple(y != x for y in  first_cols)
df[sorted(df, key=key)]

You can try to reorder like this:

first_cols = ['A','B','C']
last_cols = [col for col in df.columns if col not in first_cols]

df = df[first_cols+last_cols]

Tags:

Python

Pandas