A RetroSearch Logo

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

Search Query:

Showing content from https://www.geeksforgeeks.org/pandas/python-pandas-dataframe-sort_values-set-1/ below:

Pandas Dataframe.sort_values() - GeeksforGeeks

Pandas Dataframe.sort_values()

Last Updated : 29 Nov, 2024

In Pandas, sort_values() function sorts a DataFrame by one or more columns in ascending or descending order. This method is essential for organizing and analyzing large datasets effectively.

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

Parameter:

The output returns a sorted DataFrame with the same dimensions as the original.

Sorting DataFrame by Column

This example demonstrates how to sort a DataFrame by player names in ascending order.

Dataset Link: nba.csv

Python
import pandas as pd

# Load DataFrame from CSV file
data = pd.read_csv("nba.csv")
print("NBA Dataset:")
display(data.head())

# Sort the DataFrame by the 'Name' column in ascending order
data.sort_values("Name", axis=0, ascending=True, inplace=True, na_position='last')

# Display the sorted DataFrame
print("\nSorted DataFrame:")
display(data.head())

Output

Pandas DataFrame sorted by 'Name' Column

In the sorted DataFrame, the rows are arranged alphabetically by player names. The index may appear jumbled because sorting affects the order of rows.

Sorting DataFrame with Custom NaN Value Placement

In this example, the DataFrame is sorted by the "Salary" column, with null values positioned at the top (instead of the default last).

Python
import pandas as pd

# Load DataFrame from CSV file
data = pd.read_csv("nba.csv")

# Sort by 'Salary' column, placing NaN values at the top
data.sort_values("Salary", axis=0, ascending=True, inplace=True, na_position='first')

# Display the sorted DataFrame
print("DataFrame sorted by 'Salary' column by placing NaN values at the top:")
display(data)

Output

Here, NaN values in the 'Salary' column are placed at the top, followed by the sorted salary values.

Additionally, you can adjust the following parameters:

The sort_values() function in Pandas is a versatile tool for sorting DataFrames by specific columns, with multiple options for handling null values and choosing sorting algorithms.



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