In this tutorial, we will learn how to change the order of columns in Pandas dataframe. We can change the order of the columns in multiple. Here, we will see two ways to change the order of the columns.
First, let us load Pandas.
import pandas as pd
We will use gapminder dataset to change the column orders. Let us load gapminder dataset directly from cmdlinetips.com’s github page.
data_link = "https://raw.githubusercontent.com/cmdlinetips/data/master/gapminder-FiveYearData.csv"
df = pd.read_csv(data_link)
Our data looks like this.
df.head() country year pop continent lifeExp gdpPercap 0 Afghanistan 1952 8425333.0 Asia 28.801 779.445314 1 Afghanistan 1957 9240934.0 Asia 30.332 820.853030 2 Afghanistan 1962 10267083.0 Asia 31.997 853.100710 3 Afghanistan 1967 11537966.0 Asia 34.020 836.197138 4 Afghanistan 1972 13079460.0 Asia 36.088 739.981106
In this dataframe the columns are ordered as
df.columns.tolist() ['country', 'year', 'pop', 'continent', 'lifeExp', 'gdpPercap']
Let us say we want to change the column orders in a specific way. Here is an example order that we want.
col_order = ["continent","country", "lifeExp","pop","gdpPercap"]
Change Order of Columns in a Dataframe
One of the ways to change the column orders is to use the list containing the new column order and subset the dataframe as shown below.
df_new = df[col_order]
The resulting dataframe will contain the columns in the order we want.
df_new.head() continent country lifeExp pop gdpPercap 0 Asia Afghanistan 28.801 8425333.0 779.445314 1 Asia Afghanistan 30.332 9240934.0 820.853030 2 Asia Afghanistan 31.997 10267083.0 853.100710 3 Asia Afghanistan 34.020 11537966.0 836.197138 4 Asia Afghanistan 36.088 13079460.0 739.981106
Change Column Orders with Pandas reindex()
Another way to change the order of columns of a Pandas dataframe is to use Pandas reindex() function and use the list with the new column order we need.
Here we need to specify that we are re-indexing the columns, by using the argument “columns”.
df_new = df.reindex(columns=col_order)
df_new.head() continent country lifeExp pop gdpPercap 0 Asia Afghanistan 28.801 8425333.0 779.445314 1 Asia Afghanistan 30.332 9240934.0 820.853030 2 Asia Afghanistan 31.997 10267083.0 853.100710 3 Asia Afghanistan 34.020 11537966.0 836.197138 4 Asia Afghanistan 36.088 13079460.0 739.981106
If you are interested changing just one of the column’s position. check out Pandas insert() function to move a column to a specific location.