Q:

Sorting columns in pandas DataFrame based on column name

belongs to collection: Python Pandas Programs

0

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

All Answers

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

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

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
Count the frequency that a value occurs in a DataF... >>
<< Pandas DataFrame - Get first row value of a given ...