Q:

How to change the order of DataFrame columns?

belongs to collection: Python Pandas Programs

0

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']]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get a list from Pandas DataFrame column hea... >>
<< How to select rows from a DataFrame based on colum...