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
  • 809
  • 1
  • 8
  • 20
  • 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

3 Answers3

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
  • 74,114
  • 11
  • 41
  • 70
4

Another minimalist, (and very specific!) approach:

df = df[list('ABFCDE')]
warped
  • 8,947
  • 3
  • 22
  • 49
0
Here is a very simple answer to this(only one line). Giving littlebit more explanation to the answer from @warped

You can do that after you added the 'n' column into your df as follows.

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

df
    l   v   n
0   a   1   0
1   b   2   0
2   c   1   0
3   d   2   0

# here you can add the below code and it should work.
df = df[list('nlv')]
df

    n   l   v
0   0   a   1
1   0   b   2
2   0   c   1
3   0   d   2



However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 

import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2

df

    Upper   Lower   Net Mid Zsore
0   a       1       0   2   2
1   b       2       0   2   2
2   c       1       0   2   2
3   d       2       0   2   2

# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

   Mid  Upper   Lower   Net Zsore
0   2   a       1       0   2
1   2   b       2       0   2
2   2   c       1       0   2
3   2   d       2       0   2
rra
  • 809
  • 1
  • 8
  • 20