Pandas df.sort_values() function
df.sort_values() is a function in Pandas used to sort DataFrame data by one or more columns.
Sorting is a fundamental operation in data analysis that helps you better understand data and discover patterns.sort_values() supports sorting by single or multiple columns, ascending or descending, and can handle missing values, making it an indispensable tool in data processing.
Basic syntax and parameters
sort_values() is a member function of DataFrame, called via the dot operator . to call it.
Syntax format
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| by | str or list of str | Required | Specify the column names to sort by. If a list is given, sorting is performed sequentially in the order of the list. | None |
| axis | int or str | Optional | Specify the axis for sorting.0 or 'index' means sort by column (default);1 or 'columns' means sort by row. |
0 |
| ascending | bool or list of bool | Optional | Specify the sort order.True means ascending (from small to large);False means descending (from large to small). If a list is given, it corresponds one-to-one with by the columns in |
True |
| inplace | bool | Optional | If it is True, modify the original DataFrame directly without returning a new object; if False, a new DataFrame is returned and the original data is unchanged. |
False |
| kind | str | Optional | Specify the sorting algorithm.'quicksort'(quicksort),'mergesort'(mergesort),'heapsort'(heapsort),'stable'(stable sort). |
'quicksort' |
| na_position | str | Optional | Specify the position of missing values (NaN).'first' means place them first;'last' means place them last. |
'last' |
| ignore_index | bool | Optional | If it is True, reset the index after sorting, numbering from 0; if False, the original index is preserved. |
False |
| key | callable | Optional | apply a function to the data before sorting, often used for custom sorting rules. | None |
Return value description
- Returns a new DataFrame (if
inplace=False), orNone(ifinplace=True)。 - returns a DataFrame whose data has been sorted according to the specified rules.
Example
Let us thoroughly master sort_values() through a series of examples from simple to complex.
Example 1: Sorting by a single column in ascending order
The simplest usage is to sort by the values of a single column in ascending order.
Example
import
pandas
as
pd
Create a student score DataFrame
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Qian Qi'
]
,
'Math'
:
[
85
,
92
,
78
,
90
,
88
]
,
'English'
:
[
90
,
85
,
92
,
88
,
78
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Sort by math scores in ascending order
df_sorted
=
df.
sort_values
(
by
=
'Math'
)
(
"After sorting by math scores in ascending order:"
)
(
df_sorted
)
Expected output:
Original data:
姓名 数学 英语
0 张三 85 90
1 李四 92 85
2 王五 78 92
3 赵六 90 88
4 钱七 88 78
==================================================
# Sorted by math scores in ascending order:
姓名 数学 英语
2 王五 78 92
0 张三 85 90
4 钱七 88 78
3 赵六 90 88
1 李四 92 85
Code analysis:
- The default sorting method is ascending (from small to large).
- A math score of 78 is placed first, and 92 is placed last.
- After sorting, the index remains unchanged (2, 0, 4, 3, 1).
Example 2: Sorting by a single column in descending order
Use ascending=False can achieve descending sorting.
Example
import
pandas
as
pd
Create a student score DataFrame
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Qian Qi'
]
,
'Math'
:
[
85
,
92
,
78
,
90
,
88
]
,
'English'
:
[
90
,
85
,
92
,
88
,
78
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Sort by math scores in descending order
df_sorted
=
df.
sort_values
(
by
=
'Math'
,
ascending
=
False
)
(
"After sorting by math scores in descending order:"
)
(
df_sorted
)
Expected output:
Original data:
姓名 数学 英语
0 张三 85 90
1 李四 92 85
2 王五 78 92
3 赵六 90 88
4 钱七 88 78
==================================================
After sorting by math score in descending order:
姓名 数学 英语
1 李四 92 85
3 赵六 90 88
4 钱七 88 78
0 张三 85 90
2 王五 78 92
Code analysis:
- Use
ascending=Falsecan achieve descending sorting from large to small. - Li Si's math score of 92 is placed first.
Example 3: Sorting by multiple columns
You can sort by multiple columns: first by the first column, and when the first column has ties, by the second column.
Example
import
pandas
as
pd
Create a student score DataFrame
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Qian Qi'
]
,
'class'
:
[
'Class 1'
,
'Class 2'
,
'Class 1'
,
'Class 2'
,
'Class 1'
]
,
'Math'
:
[
85
,
92
,
78
,
90
,
88
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Sort by class first, then by math score (both ascending)
df_sorted
=
df.
sort_values
(
by
=
[
'class'
,
'Math'
]
)
(
"After sorting by class first, then by math score:"
)
(
df_sorted
)
(
"="
50
)
Sort by class ascending, math score descending
df_sorted2
=
df.
sort_values
(
by
=
[
'class'
,
'Math'
]
,
ascending
=
[
True
,
False
]
)
(
"By class ascending, math score descending:"
)
(
df_sorted2
)
Expected output:
Original data:
姓名 班级 数学
0 张三 一班 85
1 李四 二班 92
2 王五 一班 78
3 赵六 二班 90
4 钱七 一班 88
==================================================
Sorted first by class, then by math score:
姓名 班级 数学
2 王五 一班 78
0 张三 一班 85
4 钱七 一班 88
3 赵六 二班 90
1 李四 二班 92
==================================================
Sort by class ascending, math score descending:
姓名 班级 数学
4 钱七 一班 88
0 张三 一班 85
2 王五 一班 78
1 李四 二班 92
3 赵六 二班 90
Code analysis:
- Using a List
by=['班级', '数学']You can sort by multiple columns. - First sort by "Class", with Class 1 first and Class 2 after.
- Within the same class, sort by "Math" score.
- Use
ascending=[True, False]You can specify different sort directions for different columns.
Example 4: Sorting with Missing Values
Use na_position This parameter can control the position of missing values.
Example
import
pandas
as
pd
import
numpy
as
np
Create a DataFrame with missing values
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
]
,
'Score'
:
[
85
,
np.
nan
,
92
,
78
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Default: missing values are placed last
df_sorted_last
=
df.
sort_values
(
by
=
'Score'
)
(
"Missing values last:"
)
(
df_sorted_last
)
(
"="
50
)
Place missing values first
df_sorted_first
=
df.
sort_values
(
by
=
'Score'
,
na_position
=
'first'
)
(
"Missing values first:"
)
(
df_sorted_first
)
Expected output:
Original data:
姓名 成绩
0 张三 85.0
1 李四 NaN
2 王五 92.0
3 赵六 78.0
==================================================
Missing values placed at the end:
姓名 成绩
3 赵六 78.0
0 张三 85.0
2 王五 92.0
1 李四 NaN
==================================================
Missing values placed at the front:
姓名 成绩
1 李四 NaN
3 赵六 78.0
0 张三 85.0
2 王五 92.0
Code analysis:
- By default (
na_position='last'), missing values are sorted last. - Settings
na_position='first', missing values are sorted first.
Example 5: Resetting the Index After Sorting
After sorting, the index may be non-contiguous, so you can use ignore_index=True Reset the index.
Example
import
pandas
as
pd
Create a DataFrame
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
]
,
'Score'
:
[
85
,
92
,
78
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Sort without resetting the index
df_sorted
=
df.
sort_values
(
by
=
'Score'
)
(
"After sorting (original index preserved):"
)
(
df_sorted
)
(
"="
50
)
Sort and reset the index
df_sorted_reset
=
df.
sort_values
(
by
=
'Score'
,
ignore_index
=
True
)
(
"After sorting (index reset):"
)
(
df_sorted_reset
)
Expected output:
Original data:
姓名 成绩
0 张三 85
1 李四 92
2 王五 78
==================================================
排序后(保留原始索引):
姓名 成绩
2 王五 78
0 张三 85
1 李四 92
==================================================
排序后(重置索引):
姓名 成绩
0 王五 78
1 张三 85
2 李四 92
Code analysis:
- Use
ignore_index=True, the index is renumbered starting from 0. - This is more convenient when accessing data by index later.
Example 6: Custom Sorting with the key Parameter
key This parameter allows applying a custom function to the data before sorting.
Example
import
pandas
as
pd
Create a DataFrame with mixed-case strings
data
=
{
'Word'
:
[
'apple'
,
'Banana'
,
'cherry'
,
'APPLE'
,
'banana'
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
"="
50
)
Sort in ascending alphabetical order (case-sensitive)
df_sorted_case
=
df.
sort_values
(
by
=
'Word'
)
(
"Ascending alphabetical (case-sensitive):"
)
(
df_sorted_case
)
(
"="
50
)
Use the key parameter for case-insensitive sorting
df_sorted_nocase
=
df.
sort_values
(
by
=
'Word'
,
key
=
lambda
x: x.
str
.
lower
(
)
)
(
"Ascending alphabetical (case-insensitive):"
)
(
df_sorted_nocase
)
Expected output:
Original data:
单词
0 apple
1 Banana
2 cherry
3 APPLE
4 banana
==================================================
按字母升序(区分大小写):
单词
3 APPLE
0 apple
1 Banana
4 banana
2 cherry
==================================================
按字母升序(不区分大小写):
单词
0 apple
3 APPLE
1 Banana
4 banana
2 cherry
Code analysis:
- Sorting is case-sensitive by default, with uppercase letters before lowercase ones.
- Use
key=lambda x: x.str.lower()Convert all strings to lowercase before sorting to achieve case-insensitive sorting.
Example 7: In-Place Modification with the inplace Parameter
Use inplace=True You can modify the original DataFrame directly.
Example
import
pandas
as
pd
Create a DataFrame
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
]
,
'Score'
:
[
85
,
92
,
78
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
f
"Original data id: {id(df)}"
)
(
"="
50
)
Sort in place with inplace=True
df.
sort_values
(
by
=
'Score'
,
inplace
=
True
)
(
"After sorting with inplace=True:"
)
(
df
)
(
f
"Sorted data id: {id(df)}"
)
Expected output:
Original data:
姓名 成绩
0 张三 85
1 李四 92
2 王五 78
原始数据 id: 140234567890
==================================================
After sorting using inplace=True:
姓名 成绩
2 王五 78
0 张三 85
1 李四 92
排序后数据 id: 140234567890 # 同一个对象
Code analysis:
- Use
inplace=True, the DataFrame itself is modified and no new object is returned. - The ids before and after sorting
idare the same, indicating it is the same object. - This approach saves memory but modifies the original data.
Notes
sort_values()By default a new DataFrame is returned and the original data is not modified. To modify in place, useinplace=Trueparameter was added.- The sort operation is not performed in place (unless you specify
inplace=True), and the original DataFrame remains unchanged. - Use
ignore_index=TrueYou can reset the index, which is more convenient for later data processing. keyThis parameter is very powerful and enables various custom sorts, such as case-insensitive sorting and sorting by absolute value.- When sorting by multiple columns,
ascendingthis parameter can be a list, matchingbythe columns in
Common Pandas functions