To reorder existing DataFrame columns in Pandas, you can simply use indexing with a list of the desired column order. This method allows you to rearrange the columns as needed.
Example of Reordering Columns
Here’s a step-by-step example:
import pandas as pd
# Create a sample DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 92, 78],
'Age': [20, 21, 19]
}
df = pd.DataFrame(data)
# Display the original DataFrame
print("Original DataFrame:")
print(df)
# Reorder the columns
new_order = ['Score', 'Name', 'Age']
df_reordered = df[new_order]
# Display the reordered DataFrame
print("\nReordered DataFrame:")
print(df_reordered)
Explanation
- Creating the DataFrame: We first create a DataFrame
dfwith columns 'Name', 'Score', and 'Age'. - Defining New Order: We define a list
new_orderthat specifies the desired order of the columns. - Reordering: By indexing the DataFrame with
df[new_order], we create a new DataFramedf_reorderedwith the columns in the specified order. - Output: The reordered DataFrame is printed, showing 'Score' first, followed by 'Name' and 'Age'.
Important Note
- This method creates a new DataFrame. If you want to modify the original DataFrame in place, you can assign the reordered DataFrame back to the original variable:
df = df[new_order]
Further Learning
For more advanced DataFrame manipulations, consider exploring:
If you have any more questions or need additional examples, feel free to ask!
