How to change the order of DataFrame columns?

Given a DataFrame, we need change the order of columns in this DataFrame.
Submitted by Pranit Sharma, on April 10, 2022

The order of columns refers to the horizontal sequence in which the column names are created.

change the order of DataFrame columns

In the above example, the order of columns is Peter -> Harry -> Tom -> Jhon.

Sometimes we might need to rearrange this sequence. Pandas allow us to rearrange the order of columns using the loc Property.

pandas.DataFrame.loc Property

It is usually used for selecting rows and columns with the help of their names, but when it comes to rearrange the order of columns, this method is beneficial in more than one way. We can rearrange the order of all the columns or we can rearrange those columns that we want. It takes two arguments, the number of rows and the number of columns. Defining a colon (:) means selecting all the rows followed by a comma and a list of rearranged column names is the actual syntax to accomplish the task.

Syntax:

property DataFrame.loc

# Example
df.loc[:,['col_name','col_name','col_name','col_name']]

Example:

# Importing Pandas library
import pandas as pd

# Creating a dictionary
d = {
    'Countries':['USA','UK','Russia','India','China'],
    'Size':['9.834 m sq km','242,495 sq km','17.1 m sq km','3.287 m sq km',
    '9.597 m sq km'],
    'Population':[332915073,68510300,146044010,1380004385,1439323776],
    'GDP':['$22.99 trillion','$2709.68 billion',
    '$1,690,050 million','$2.87 trillion','$17.7 trillion'],
    'Currency':['US  dollar','Pound','Ruble','Rupees','Renminbi']
}

# Creating DataFrame
df = pd.DataFrame(d)

# Printing dataframe
print("\n")
print("Original Dataframe\n",df,"\n")


# Current order of columns is 
# Countries -> Size -> Population -> GDP -> Currency
# Using loc method for re-arranging the columns, 
# we will store it in new variable
new_df = df.loc[:,['Countries','Population','Size','Currency','GDP']]

# Printing dataframe with re-arranged columns
print("Re-arranged columns:\n",new_df)

Output:

change the order of DataFrame columns | Output

Explanation:

In the above example, we have passed a list of column names with the new sequence. An important point is that we will pass the list after defining the number of rows. Here, we have selected all the rows.

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.