ADVERTISEMENT
ADVERTISEMENT

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). Sorting in pandas DataFrame is required for effective analysis of the data. Pandas allow us to sort the DataFrame using DataFrame.sort_index() method.

pandas.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

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# 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:

Output | Sorting Columns

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.