"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Move a Pandas DataFrame Column to the Beginning?

How to Move a Pandas DataFrame Column to the Beginning?

Posted on 2025-03-22
Browse:668

How to Move a Pandas DataFrame Column to the Beginning?

How to Reorder DataFrame Column Order

In pandas, DataFrames consist of both rows and columns, with each column representing a separate feature or variable. The order of these columns is significant for data analysis and manipulation.

Problem: Rearranging Column Order

Consider the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

After adding an additional column, let's say 'mean', via assignment:

df['mean'] = df.mean(1)

The objective is to move the 'mean' column to the front, making it the first column in the DataFrame, while preserving the order of the remaining columns.

Solution: Reordering Columns

An effective method to reorder columns is by re-assigning the DataFrame with a modified list of columns.

Step 1: Obtain Column List as Array

cols = df.columns.tolist()

This will result in an array containing the column names in their current order.

Step 2: Rearrange Column Order

Rearrange the column order within the list as desired. In this case, to move 'mean' to the beginning:

cols = cols[-1:]   cols[:-1]

Step 3: Reorder DataFrame Columns

Reorder the DataFrame using the rearranged column list:

df = df[cols]  # or df = df.ix[:, cols]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3