1

I have a pandas data frame and I want to move the "F" column to after the "B" column. Is there a way to do that?

   A  B  C    D  E  F
0  7  1       8  1  6
1  8  2  5    8  5  8
2  9  3  6    8     5
3  1     8    1  3  4
4  6  8  2    5  0  9
5     2  N/A  1  3  8


df2
   A  B  F  C    D  E  
0  7  1  6       8  1  
1  8  2  8  5    8  5  
2  9  3  5  6    8     
3  1     4  8    1  3  
4  6  8  9  2    5  0  
5     2  8  N/A  1  3  

So it should finally look like df2. Thanks in advance.

rra
  • 655
  • 4
  • 14
  • Does this answer your question? [how do I insert a column at a specific column index in pandas?](https://stackoverflow.com/questions/18674064/how-do-i-insert-a-column-at-a-specific-column-index-in-pandas) & [Move column by name to front of table in pandas](https://stackoverflow.com/questions/25122099/move-column-by-name-to-front-of-table-in-pandas) – Trenton McKinney Jun 17 '20 at 15:46

2 Answers2

6

You can try df.insert + df.pop after getting location of B by get_loc

df.insert(df.columns.get_loc("B")+1,"F",df.pop("F"))
print(df)

     A  B    F    C  D    E
0  7.0  1  6.0  NaN  8  1.0
1  8.0  2  8.0  5.0  8  5.0
2  9.0  3  5.0  6.0  8  NaN
3  1.0  8  NaN  1.0  3  4.0
4  6.0  8  9.0  2.0  5  0.0
5  NaN  2  8.0  NaN  1  3.0
anky
  • 71,373
  • 8
  • 36
  • 64
4

Another minimalist, (and very specific!) approach:

df = df[list('ABFCDE')]
warped
  • 8,032
  • 3
  • 21
  • 43