Home >Backend Development >Python Tutorial >How to Move a Pandas DataFrame Column to the Beginning?
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.
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.
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!