How to sort pandas data frame in python?

Description

To sort the pandas data frame by its values and columns using python.

   Import the library.

   Read the sample data set.

   column in an ascending order.

   column in an descending order.

   Sort by multiple columns.

#import libraries

import pandas as pd

#read the data set

data=pd.read_csv(‘/home/soft27/soft27

/Sathish/Pythonfiles/Employee.csv’)

#creating data frame

df=pd.DataFrame(data)

print(“Actual data frame\n”,df)

#sorting in ascending

print(“Sorting in ascending order”)

print(df.sort_values(by=[‘rating’],inplace=False))

#sorting in descending

print(“Sorting in descending order”)

print(df.sort_values(by=[‘salary’],inplace=False,

ascending=False))

#sort multiple columns in ascending

print(“Ascending by multiple columns”)

print(df.sort_values(by=[‘age’,’salary’], inplace=False))

#sort multiple columns in descending

print(“Descending by multiple columns”)

print(df.sort_values(by=

[‘salary’,’age’], inplace=False, ascending=False))

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit