jscriptor
jscriptor

Reputation: 845

position or move pandas column to a specific column index

I have a DF mydataframe and it has multiple columns (over 75 columns) with default numeric index:

Col1 Col2 Col3 ... Coln

I need to arrange/change position to as follows:

Col1 Col3 Col2 ... Coln 

I can get the index of Col2 using:

mydataframe.columns.get_loc("Col2")

but I don't seem to be able to figure out how to swap, without manually listing all columns and then manually rearrange in a list.

Upvotes: 1

Views: 3253

Answers (4)

Andy L.
Andy L.

Reputation: 25259

Using np.r_ to create array of column index:

Given sample as follows:

df:
   col1  col2  col3  col4  col5  col6  col7  col8  col9  col10
0     0     1     2     3     4     5     6     7     8      9
1    10    11    12    13    14    15    16    17    18     19


i, j = df.columns.slice_locs('col2', 'col10')
df[df.columns[np.r_[:i, i+1, i, i+2:j]]]

Out[142]:
   col1  col3  col2  col4  col5  col6  col7  col8  col9  col10
0     0     2     1     3     4     5     6     7     8      9
1    10    12    11    13    14    15    16    17    18     19

Upvotes: 0

piRSquared
piRSquared

Reputation: 294358

I'm imagining you want what @sentence is assuming. You want to swap the positions of 2 columns regardless of where they are.

This is a creative approach:

  1. Create a dictionary that defines which columns get switched with what.
  2. Define a function that takes a column name and returns an ordering.
  3. Use that function as a key for sorting.

d = {'Col3': 'Col2', 'Col2': 'Col3'}
k = lambda x: df.columns.get_loc(d.get(x, x))

df[sorted(df, key=k)]

   Col0  Col1  Col3  Col2  Col4
0     0     1     3     2     4
1     5     6     8     7     9
2    10    11    13    12    14
3    15    16    18    17    19
4    20    21    23    22    24

Setup

df = pd.DataFrame(
    np.arange(25).reshape(5, 5)
).add_prefix('Col')

Upvotes: 0

sentence
sentence

Reputation: 8923

How to proceed:

  1. store the names of columns in a list;
  2. swap the names in that list;
  3. apply the new order on the dataframe.

code:

l = list(df)

i1, i2 = l.index('Col2'), l.index('Col3')
l[i2], l[i1] = l[i1], l[i2]

df = df[l]

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150765

Try:

new_cols = [Col1, Col3, Col2] + df.columns[3:]

df = df[new_cols]

Upvotes: 3

Related Questions