Skip to content

How to change the order of DataFrame columns?

To change the order of columns in a Pandas DataFrame, you can use the DataFrame's "reindex" method and specify the new order of the columns.

For example, if you have a DataFrame named "df" with columns ["A", "B", "C"], and you want to change the order of the columns to ["C", "B", "A"], you can do so by using the following code:

Change the order of a Pandas DataFrame's columns in Python, using the reindex method

python
df = df.reindex(columns=["C", "B", "A"])

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

Alternatively, you can use the DataFrame's "columns" attribute to directly assign a new list of column names to the DataFrame. For example:

Reassign a Pandas DataFrame's columns in Python, using the columns method

python
df.columns = ["C", "B", "A"]

Both of these approaches will change the order of the columns in the DataFrame, and the resulting DataFrame will have columns "C", "B", and "A" in that order.

Dual-run preview — compare with live Symfony routes.