Pandas >> How to Change the Order of DataFrame Columns

2021-11-23 Pandas

Table of Contents

[Pandas] How to change column order

In this article, we will talk about how to change columns order and columns list of DataFrame in Pandas.

Firstly, we prepare data for demonstration.

Preparing data

import pandas as pd

df = pd.DataFrame({
    "name": ["Kevin", "Jack", "Mary"],
    "score": [80, 90, 95],
    "class": ["A", "B", "A"],
    "sex": ["M", "M", "F"]
}, index=["K", "J", "M"])

df

Result

name score class sex
K Kevin 80 A M
J Jack 90 B M
M Mary 95 A F

1. Get current column list

We can use columns property of DataFrame to get the column names of DataFrame and use tolist() method to change the column names to a plain python string list.

cols = df.columns.tolist()
cols

Result

['name', 'score', 'class', 'sex']

2. Change the order of columns

We can change the order of column name in the list and get a new list of columns.

We change sex columns to second position.

cols2 = cols[0:1] + cols[-1:] + cols[1:-1]
cols2

Result

['name', 'sex', 'score', 'class']

3. Apply new columns list to DataFrame

We can use square brackets of DataFrame to get a new DataFrame with columns in new order.

We change sex columns to second position.

df2 = df[cols2]
df2

Result

name sex score class
K Kevin M 80 A
J Jack M 90 B
M Mary F 95 A

Of course we can specify the column list directly to change the column order and columns.

df3 = df[["class", "name", "score"]]
df3

Result

class name score
K A Kevin 80
J B Jack 90
M A Mary 95

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us