Home >Backend Development >Python Tutorial >How to Move a Pandas DataFrame Column to the Beginning?

How to Move a Pandas DataFrame Column to the Beginning?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 06:27:31184browse

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]

The above is the detailed content of How to Move a Pandas DataFrame Column to the Beginning?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn