pandas how to swap or reorder columns

Yun Tae Hwang picture Yun Tae Hwang · Nov 4, 2018 · Viewed 26.6k times · Source

I know that there are ways to swap the column order in python pandas. Let say I have this example dataset:

import pandas as pd    
employee = {'EmployeeID' : [0,1,2],
     'FirstName' : ['a','b','c'],
     'LastName' : ['a','b','c'],
     'MiddleName' : ['a','b', None],
     'Contact' : ['(M) 133-245-3123', '(F)[email protected]', '(F)312-533-2442 [email protected]']}

df = pd.DataFrame(employee)

The one basic way to do would be:

neworder = ['EmployeeID','FirstName','MiddleName','LastName','Contact']
df=df.reindex(columns=neworder)

However, as you can see, I only want to swap two columns. It was doable just because there are only 4 column, but what if I have like 100 columns? what would be an effective way to swap or reorder columns?

There might be 2 cases:

  1. when you just want 2 columns swapped.
  2. when you want 3 columns reordered. (I am pretty sure that this case can be applied to more than 3 columns.)

Thank you guys.

Answer

sanster9292 picture sanster9292 · Mar 17, 2019

Say your current order of column is [b,c,d,a] and you want to order it into [a,b,c,d], you could do it this way:

new_df = old_df[['a', 'b', 'c', 'd']]