How to change the order of DataFrame columns?
Change order of columns:
import pandas as pd df = pd.DataFrame({'Age': [30, 20, 22, 40, 32, 28, 39], 'Color': ['Blue', 'Green', 'Red', 'White', 'Gray', 'Black', 'Red'], 'Food': ['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'], 'Height': [165, 70, 120, 80, 180, 172, 150], 'Score': [4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2], 'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX'] }, index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia']) print("\n -- Change order using columns -- \n") new_order = [3, 2, 1, 4, 5, 0] df = df[df.columns[new_order]] print(df) print("\n -- Change order using reindex -- \n") df = df.reindex(['State', 'Color', 'Age', 'Food', 'Score', 'Height'], axis=1) print(df)
C:\python\pandas examples>pycodestyle --first example15.py C:\python\pandas examples>python example15.py -- Change order using columns -- Height Food Color Score State Age Jane 165 Steak Blue 4.6 NY 30 Nick 70 Lamb Green 8.3 TX 20 Aaron 120 Mango Red 9.0 FL 22 Penelope 80 Apple White 3.3 AL 40 Dean 180 Cheese Gray 1.8 AK 32 Christina 172 Melon Black 9.5 TX 28 Cornelia 150 Beans Red 2.2 TX 39 -- Change order using reindex -- State Color Age Food Score Height Jane NY Blue 30 Steak 4.6 165 Nick TX Green 20 Lamb 8.3 70 Aaron FL Red 22 Mango 9.0 120 Penelope AL White 40 Apple 3.3 80 Dean AK Gray 32 Cheese 1.8 180 Christina TX Black 28 Melon 9.5 172 Cornelia TX Red 39 Beans 2.2 150 C:\python\pandas examples>
2018-10-23T00:31:40+05:30
2018-10-23T00:31:40+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution