Sorting columns in pandas DataFrame based on column name

Given a DataFrame, we have to sort columns based on the column name.
Submitted by Pranit Sharma, on April 28, 2022

Sorting refers to rearranging a series or a sequence in particular fashion (ascending, descending or in any specific pattern).

Problem statement

Given a DataFrame, we have to sort columns based on the column name.

Sorting columns in pandas DataFrame based on column name

Sorting in pandas DataFrame is required for effective analysis of the data. Pandas allow us to sort the DataFrame using DataFrame.sort_index() method. This method sorts the object passed inside it as a parameter based on the condition defined inside it as a parameter.

Syntax

DataFrame.sort_index(
    axis=0, 
    level=None, 
    ascending=True, 
    inplace=False, 
    kind='quicksort', 
    na_position='last', 
    sort_remaining=True, 
    ignore_index=False, 
    key=None
    )

Parameter(s)

It takes different parameters which are dependent on what object is need to be sorted.

  • axis = 0: axis refers to the column.
  • Ascending = True: It means we want the object to be sorted in ascending order.
  • Descending = True: It means we want the object to be sorted in descending order.
  • inplace = True: If this is defined as True, it means that we want to perform operations in place and the changes will be occur in the original DataFrame otherwise a new sorted DataFrame would be returned
Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example.

Python program for sorting columns in pandas DataFrame based on column name

# Importing pandas package
import pandas as pd

# Creating a Dictionary
dict = {
    'Name':['Amit','Bhairav','Chirag','Divyansh','Esha'],
    'DOB':['07/12/2001','08/11/2002','09/10/2003','10/09/2004','11/08/2005'],
    'Gender':['Male','Male','Male','Male','Female']
}

# Creating a DataFrame
df = pd.DataFrame(dict)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Sorting the DataFrame based on column 1
sorted_df = df.sort_index(axis=1)

# Display sorted DataFrame
print("Sorted DataFrame: \n",sorted_df)

Output

The output of the above program is:

Output | Sorting Columns

Python Pandas Programs »

Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.