Python | Pandas dataframe.sort_index()

13 Jun, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.sort_index() function sorts objects by labels along the given axis. Basically the sorting algorithm is applied on the axis labels rather than the actual data in the dataframe and based on that the data is rearranged. We have the freedom to choose what sorting algorithm we would like to apply. There are three possible sorting algorithms that we can use ‘quicksort’, ‘mergesort’ and ‘heapsort’. 
Syntax: DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True, by=None)Parameters : axis : index, columns to direct sorting level : if not None, sort on values in specified index level(s) ascending : Sort ascending vs. descending inplace : 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. Not implemented for MultiIndex. sort_remaining : If true and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified levelReturn : sorted_obj : DataFrame  
For link to the CSV file used in the code, click hereExample #1: Use sort_index() function to sort the dataframe based on the index labels. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # Print the dataframedf
As we can see in the output, the index labels are already sorted i.e. (0, 1, 2, ....). So we are going to extract a random sample out of it and then sort it for the demonstration purpose.Lets extract a random sample of 15 elements from the dataframe using dataframe.sample() function. 
Python3
# extract the sample dataframe from "df"# and store it in "sample_df"sample_df = df.sample(15) # Print the sample data framesample_df
Note : Every time we execute dataframe.sample() function, it will give different output. Let’s use the dataframe.sort_index() function to sort the dataframe based on the index labels 
Python3
# sort by index labelssample_df.sort_index(axis = 0)
Output :  
As we can see in the output, the index labels are sorted.   Example #2: Use sort_index() function to sort the dataframe based on the column labels. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # sorting based on column labelsdf.sort_index(axis = 1)
Output :  
 
Python | Pandas dataframe.sort_index() | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython | Pandas dataframe.sort_index() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uxPYPnxI9N0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
anikakapoor
vinayedula
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Check if element exists in list in Python