Search code examples
pythonpandasmultiple-columnsswap

pandas how to swap or reorder columns


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)a123@gmail.com', '(F)312-533-2442 jimmy234@gmail.com']}

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.)

Solution

  • Two column Swapping

    cols = list(df.columns)
    a, b = cols.index('LastName'), cols.index('MiddleName')
    cols[b], cols[a] = cols[a], cols[b]
    df = df[cols]
    

    Reorder column Swapping (2 swaps)

    cols = list(df.columns)
    a, b, c, d = cols.index('LastName'), cols.index('MiddleName'), cols.index('Contact'), cols.index('EmployeeID')
    cols[a], cols[b], cols[c], cols[d] = cols[b], cols[a], cols[d], cols[c]
    df = df[cols]
    

    Swapping Multiple

    Now it comes down to how you can play with list slices -

    cols = list(df.columns)
    cols = cols[1::2] + cols[::2]
    df = df[cols]