fred.schwartz
fred.schwartz

Reputation: 2155

Reorder certain columns in pandas dataframe

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

Upvotes: 12

Views: 10983

Answers (3)

mozway
mozway

Reputation: 260600

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

Upvotes: 1

piRSquared
piRSquared

Reputation: 294258

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

Upvotes: 8

Quang Hoang
Quang Hoang

Reputation: 150735

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]

Upvotes: 33

Related Questions