0

There are a few solutions to reverse the order of all columns here on SO like for example so:

df = df.iloc[:,::-1]

What I want to achieve is only reverse the order of columns starting from column 2 on, so I want to keep A and B in the same place and only reverse the order of the columns after that. As I have a couple of hundred columns and don't want to write the order manually.

My initial columns are:

| A | B | C | D | E | F |
|---|---|---|---|---|---|

And The Result I am looking for is:

| A | B | F | E | D | C |
|---|---|---|---|---|---|

Thanks!

ufulu
  • 83
  • 4
  • Does this answer your question? [How to change the order of DataFrame columns?](https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns) – AMC Dec 03 '19 at 08:46

2 Answers2

0
df[list(df.columns[:2]) + list(df.columns[:1:-1])]
mcsoini
  • 6,280
  • 2
  • 15
  • 38
0

Use numpy.r_ for concatenate of indices and tehn select by DataFrame.iloc:

df = pd.DataFrame(columns=list('ABCDEF'))

print (df.iloc[:, np.r_[0:2, len(df.columns)-1:1:-1]])
Empty DataFrame
Columns: [A, B, F, E, D, C]
Index: []

Or seelct both DataFrames with join:

print (df.iloc[:, :2].join(df.iloc[:, :1:-1]))
Empty DataFrame
Columns: [A, B, F, E, D, C]
Index: []
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252