w3resource

Reordering DataFrame columns in Pandas


14. Reordering Columns in a DataFrame

Write a Pandas program to reorder columns in a DataFrame.

This exercise demonstrates how to reorder the columns in a DataFrame.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with mixed column order
df = pd.DataFrame({
    'Age': [25, 30, 22],
    'Name': ['Selena', 'Annabel', 'Caeso'],
    'Salary': [50000, 60000, 70000]
})

# Reorder columns to 'Name', 'Age', 'Salary'
df_reordered = df[['Name', 'Age', 'Salary']]

# Output the result
print(df_reordered)

Output:

      Name  Age  Salary
0   Selena   25   50000
1  Annabel   30   60000
2    Caeso   22   70000

Explanation:

  • Created a DataFrame with columns in mixed order.
  • Reordered the columns manually by passing the desired column order to df[].
  • Outputted the DataFrame with the columns in the desired order.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to reorder columns in a DataFrame based on a custom list provided by the user.
  • Write a Pandas program to move the last column of a DataFrame to the first position without altering the order of other columns.
  • Write a Pandas program to reorder columns alphabetically and then reverse the order of the DataFrame.
  • Write a Pandas program to reorder columns based on the data type of each column, grouping numeric and non-numeric columns separately.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.