pandas how to swap or reorder columns pandas how to swap or reorder columns python python

pandas how to swap or reorder columns


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']]


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]


When faced with same problem at larger scale, I came across a very elegant solution at this link: http://www.datasciencemadesimple.com/re-arrange-or-re-order-the-column-of-dataframe-in-pandas-python-2/ under the heading"Rearrange the column of dataframe by column position in pandas python".

Basically if you have the column order as a list, you can read that in as the new column order.

##### Rearrange the column of dataframe by column position in pandas pythondf2=df1[df1.columns[[3,2,1,0]]]print(df2)

In my case, I had a pre-calculated column linkage that determined the new order I wanted. If this order was defined as an array in L, then:

a_L_order = a[a.columns[L]]