How To Change The Order Of Columns In Pandas | Towards Data Science

Reordering columns in pandas DataFrames is one of the most common operations we want to perform. This is usually useful when it comes down to presenting results to other people as we need to order (at least a few) columns in some logical order.
In today’s article we are going to discuss how to change the order of columns in pandas DataFrames using
slicing of the original frame — mostly relevant when you need to re-order most of the columns
insert() method — if you want to insert a single column into a specified index
set_index() — if you need to move a column to the front of the DataFrame
and, reindex() method — mostly relevant to cases where you can specify column indices in the order you wish them to appear (e.g. in alphabetical order)
First, let’s create an example DataFrame that we’ll reference throughout this guide.
import pandas as pddf = pd.DataFrame({    'colA':[1, 2, 3],     'colB': ['a', 'b', 'c'],    'colC': [True, False, False],    'colD': [10, 20, 30],})print(df)#    colA colB   colC  colD# 0     1    a   True    10# 1     2    b  False    20# 2     3    c  False    30
The easiest way is to slice the original DataFrame using a list containing the column names in the new order you wish them to follow:
df = df[['colD', 'colB', 'colC', 'colA']]print(df)#    colD colB   colC  colA# 0    10    a   True     1# 1    20    b  False     2# 2    30    c  False     3
This method is probably good enough if you want to re-order most of the columns’ names (and probably your DataFrame does have too many columns).
If you need to insert column into DataFrame at specified location then pandas.DataFrame.insert() should do the trick. However, you should make sure that the column is first taken out of the original DataFrame otherwise a ValueError will be raised with the following message:
ValueError: cannot insert column_name, already exists
Therefore, before calling insert() we first need to do a pop() over the DataFrame in order to drop the column from the original DataFrame and retain its information. For instance, if we want to place colD as the first column of the frame we first need to pop() the column and then insert it back, this time to the desired index.
col = df.pop("colD")df.insert(0, col.name, col)print(df)#    colD  colA colB   colC# 0    10     1    a   True# 1    20     2    b  False# 2    30     3    c  False
If you want to move a column to the front of a pandas DataFrame, then set_index() is your friend.
First, you specify the column we wish to move to the front, as the index of the DataFrame and then reset the index so that the old index is added as a column, and a new sequential index is used. Again, notice how we pop() the column so that it gets dropped before is being added as an index. This is required otherwise a name collision will occur when attempting to make the old index the first column of the DataFrame.
df.set_index(df.pop('colD'), inplace=True)#       colA colB   colC # colD# 10       1    a   True# 20       2    b  False# 30       3    c  Falsedf.reset_index(inplace=True)#    colD  colA colB   colC# 0    10     1    a   True# 1    20     2    b  False# 2    30     3    c  False
Finally, if you want to specify column indices in the order you wish them to appear (e.g. in alphabetical order) you can use reindex() method to conform the DataFrame to new index.
For example, let’s suppose we need to order the column names alphabetically in descending order
df = df.reindex(columns=sorted(df.columns, reverse=True))#    colD   colC colB  colA# 0    10   True    a     1# 1    20  False    b     2# 2    30  False    c     3
Note that the above is equivalent to
df.reindex(sorted(df.columns, reverse=True), axis='columns')
In today’s short guide we discussed how to change the order of columns in pandas DataFrames in many different ways. Make sure you pick the right method based on your specific requirements.
You may also like