How to reorder existing DataFrame columns?

0156

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

  1. Creating the DataFrame: We first create a DataFrame df with columns 'Name', 'Score', and 'Age'.
  2. Defining New Order: We define a list new_order that specifies the desired order of the columns.
  3. Reordering: By indexing the DataFrame with df[new_order], we create a new DataFrame df_reordered with the columns in the specified order.
  4. 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!

0 Comments

no data
Be the first to share your comment!