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]
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