0
0
Pandasdata~5 mins

sort_values() by single column in Pandas

Choose your learning style9 modes available
Introduction

We use sort_values() to arrange data in order based on one column. This helps us see data from smallest to largest or vice versa.

When you want to see the top or bottom values in a list, like highest sales.
When you need to organize data by date to see events in order.
When preparing data for reports where order matters.
When cleaning data and checking for outliers by sorting values.
When comparing values easily by sorting them.
Syntax
Pandas
DataFrame.sort_values(by='column_name', ascending=True)

by is the column name to sort by.

ascending=True sorts from smallest to largest. Use False for largest to smallest.

Examples
Sorts the DataFrame df by the column age in ascending order.
Pandas
df.sort_values(by='age')
Sorts df by score from highest to lowest.
Pandas
df.sort_values(by='score', ascending=False)
Sample Program

This code creates a small table of names and ages. Then it sorts the table by age from youngest to oldest and prints the result.

Pandas
import pandas as pd

data = {'name': ['Anna', 'Bob', 'Charlie', 'Diana'],
        'age': [28, 22, 35, 30]}
df = pd.DataFrame(data)

# Sort by age ascending
sorted_df = df.sort_values(by='age')
print(sorted_df)
OutputSuccess
Important Notes

Sorting does not change the original DataFrame unless you use inplace=True.

If the column has missing values, they appear at the end by default.

Summary

sort_values() helps order data by one column.

Use ascending=True for smallest to largest, False for largest to smallest.

It returns a new sorted DataFrame unless inplace=True is set.