How to do sort in panda dataframes -python
In this tutorial, you will learn how to do sorting in dataframe using pandas in python. you can do by using pandas inbuilt function sort_values()
Syntax : DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Parameters :
by : str or list of str
Name or list of names which refer to the axis items.
axis : {0 or ‘index’, 1 or ‘columns’}, default 0
Axis to direct sorting
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.
inplace : bool, default False
if True, perform operation in-place
kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’
Choice of sorting algorithm. See also ndarray.np.sort for more information. mergesort is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label.
na_position : {‘first’, ‘last’}, default ‘last’
first puts NaNs at the beginning, last puts NaNs at the end
import pandas as pd
data = pd.DataFrame({'id':[6,1,2,8,3,4],
'name':['ravi','david','raju','david','kumar','teju'],
'salaries':['15000','20000','30000','45389','50000','20000']
})
print('Before sorting \n',data)
print('After sorting by ID \n',data.sort_values(by='id', ascending = True))
print('After sorting by Names \n',data.sort_values(by='name', ascending = True))
print('After sorting by Salaries \n',data.sort_values(by='salaries', ascending = True))
Output:
Before sorting id name salaries 0 6 ravi 15000 1 1 david 20000 2 2 raju 30000 3 8 david 45389 4 3 kumar 50000 5 4 teju 20000 After sorting by ID id name salaries 1 1 david 20000 2 2 raju 30000 4 3 kumar 50000 5 4 teju 20000 0 6 ravi 15000 3 8 david 45389 After sorting by Names id name salaries 1 1 david 20000 3 8 david 45389 4 3 kumar 50000 2 2 raju 30000 0 6 ravi 15000 5 4 teju 20000 After sorting by Salaries id name salaries 0 6 ravi 15000 1 1 david 20000 5 4 teju 20000 2 2 raju 30000 3 8 david 45389 4 3 kumar 50000