- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Reverse the column order of the Pandas DataFrame
To reverse the column order, use the dataframe.columns and set as -1 −
dataFrame[dataFrame.columns[::-1]
At first, import the required library −
import pandas as pd
Create a DataFrame with 4 columns −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] })
Reverse the column order −
df = dataFrame[dataFrame.columns[::-1]]
Example
Following is the code −
import pandas as pd # creating dataframe dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] }) print"DataFrame ...\n",dataFrame # reversing the dataframe columns df = dataFrame[dataFrame.columns[::-1]] print"\nReversed DataFrame....\n", df
Output
This will produce the following output −
DataFrame ... Car Cubic_Capacity Reg_Price Units_Sold 0 BMW 2000 7000 100 1 Lexus 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 110 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 250 Reversed DataFrame.... Units_Sold Reg_Price Cubic_Capacity Car 0 100 7000 2000 BMW 1 120 1500 1800 Lexus 2 150 5000 1500 Tesla 3 110 8000 2500 Mustang 4 200 9000 2200 Mercedes 5 250 6000 3000 Jaguar
Advertisements
To Continue Learning Please Login
Login with Google