Reordering DataFrame columns in Pandas
Pandas: Data Cleaning and Preprocessing Exercise-14 with Solution
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/pandas/pandas-reorder-dataframe-columns.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics