Reputation: 845
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
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
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:
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
df = pd.DataFrame(
np.arange(25).reshape(5, 5)
).add_prefix('Col')
Upvotes: 0
Reputation: 8923
How to proceed:
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
Reputation: 150765
Try:
new_cols = [Col1, Col3, Col2] + df.columns[3:]
df = df[new_cols]
Upvotes: 3