Pandas: How to reorder columns

Summary: in this tutorial, you’ll learn about how to reorder and swap columns on a DataFrame.

Reorder columns

There are two ways you can reorder columns in Pandas. Basically you have to align your DataFrame to another column labels. Let’s see a simple example.

df = pd.DataFrame({'month': [1, 4, 7, 10], 'year': [2012, 2014, 2013, 2014], 'sale': [55, 40, 84, 31]}, index=['a','b','d','e'])
Code language: Python (python)
monthyearsale
a1201255
b4201440
d7201384
e10201431

The first way to reorder columns is to select columns out of the DataFrame use Pandas []. We need to passing a list of column names to DataFrame attribute selector in order to create a new DataFrame, then assign the old name to the new one.

df = df[['sale', 'month', 'year']]
Code language: Python (python)
salemonthyear
a5512012
b4042014
d8472013
e31102014

Alternatively, you can also change the order of the columns using Pandas reindex() method. Please note that the function returns a new DataFrame object, leaving the original one in place.

df = pd.DataFrame({'month': [1, 4, 7, 10], 'year': [2012, 2014, 2013, 2014], 'sale': [55, 40, 84, 31]}, index=['a','b','d','e']) df = df.reindex(columns=['sale', 'month', 'year']) df
Code language: Python (python)
salemonthyear
a5512012
b4042014
d8472013
e31102014

Get the column names as a list

If you have a large number of columns and don’t want to type them all over again, you can easily get them as a list using df.columns.

import pandas as pd # Import data from Open Brewery DB df = pd.read_csv("https://github.com/openbrewerydb/openbrewerydb/raw/master/data/united-states/hawaii.csv") list(df.columns)
Code language: Python (python)

Output :

['obdb_id', 'name', 'brewery_type', 'street', 'address_2', 'address_3', 'city', 'state', 'county_province', 'postal_code', 'website_url', 'phone', 'created_at', 'updated_at', 'country', 'longitude', 'latitude', 'tags']
Code language: Python (python)

Leave a Comment