A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-pandas-dataframe-sort_index/ below:

Pandas dataframe.sort_index() - GeeksforGeeks

Pandas dataframe.sort_index()

Last Updated : 23 Dec, 2024

Pandas is one of those packages and makes importing and analyzing data much easier. When working with DataFrames, Pandas is used for handling tabular data. Let's learn Pandas DataFrame sort_index() method, which is used to sort the DataFrame based on index or column labels.

Pandas sort_index() function sorts a DataFrame by its index labels (row labels) or column labels. This method allows us to rearrange the data based on the axis labels, without changing the data itself. It’s important to note that you can choose the sorting algorithm: quicksort, mergesort, or heapsort. The default is quicksort.
 

Syntax: DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None)

Parameters of sort_index()

How Does sort_index() Work?

You can get the csv file here .

Example 1: Sort DataFrame by Index Labels

Python
# importing pandas as pd
import pandas as pd

# Creating the dataframe 
df = pd.read_csv("nba.csv")

# Print the dataframe
df

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.

Python
# extract the sample dataframe from "df"
# and store it in "sample_df"
sample_df = df.sample(15)

# Print the sample data frame
sample_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
 

Python
# sort by index labels
sample_df.sort_index(axis = 0)

Output : 


As we can see in the output, the index labels are sorted. 
  
Example 2: Sort DataFrame by Column Labels

Python
# importing pandas as pd
import pandas as pd

# Creating the dataframe 
df = pd.read_csv("nba.csv")

# sorting based on column labels
df.sort_index(axis = 1)

Output : 


sort_index() function in Pandas sorts the DataFrame by index or columns. By understanding the parameters like axis, ascending, and kind, you can customize the sorting behavior to suit your needs.


Pandas dataframe.sort_index()


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4