Reorder certain columns in pandas dataframe

Question:

I have a dataframe, with the following columns, in this order;

'2','4','9','A','1','B','C'

I want the first 3 columns to be ABC but the rest it doesn’t matter.

Output:

'A','B','C','3','2','9'... and so on

Is this possible?

(there are 100’s of columns, so i can’t put them all in a list

Asked By: fred.schwartz

||

Answers:

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]
Answered By: Quang Hoang

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)]
Answered By: piRSquared

Using columns.difference:

first = ['A', 'B', 'C']

out = df[first+list(df.columns.difference(first, sort=False))]

Or, if there is a chance that a name from first is not present in df:

first = ['A', 'B', 'C']

out = df.reindex(columns=first+list(df.columns.difference(first, sort=False)))
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.