Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.sort_values() function

Pandas df.sort_values() function

Pandas Common Functions Common Pandas functions


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


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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Sort by math scores in ascending order

df_sorted

=

df.

sort_values

(

by

=

'Math'

)

print

(

"After sorting by math scores in ascending order:"

)

print

(

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:

  1. The default sorting method is ascending (from small to large).
  2. A math score of 78 is placed first, and 92 is placed last.
  3. 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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Sort by math scores in descending order

df_sorted

=

df.

sort_values

(

by

=

'Math'

,

ascending

=

False

)

print

(

"After sorting by math scores in descending order:"

)

print

(

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:

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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Sort by class first, then by math score (both ascending)

df_sorted

=

df.

sort_values

(

by

=

[

'class'

,

'Math'

]

)

print

(

"After sorting by class first, then by math score:"

)

print

(

df_sorted

)

print

(

"="

50

)

Sort by class ascending, math score descending

df_sorted2

=

df.

sort_values

(

by

=

[

'class'

,

'Math'

]

,

ascending

=

[

True

,

False

]

)

print

(

"By class ascending, math score descending:"

)

print

(

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:

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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Default: missing values are placed last

df_sorted_last

=

df.

sort_values

(

by

=

'Score'

)

print

(

"Missing values last:"

)

print

(

df_sorted_last

)

print

(

"="

50

)

Place missing values first

df_sorted_first

=

df.

sort_values

(

by

=

'Score'

,

na_position

=

'first'

)

print

(

"Missing values first:"

)

print

(

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:

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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Sort without resetting the index

df_sorted

=

df.

sort_values

(

by

=

'Score'

)

print

(

"After sorting (original index preserved):"

)

print

(

df_sorted

)

print

(

"="

50

)

Sort and reset the index

df_sorted_reset

=

df.

sort_values

(

by

=

'Score'

,

ignore_index

=

True

)

print

(

"After sorting (index reset):"

)

print

(

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:

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

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Sort in ascending alphabetical order (case-sensitive)

df_sorted_case

=

df.

sort_values

(

by

=

'Word'

)

print

(

"Ascending alphabetical (case-sensitive):"

)

print

(

df_sorted_case

)

print

(

"="

50

)

Use the key parameter for case-insensitive sorting

df_sorted_nocase

=

df.

sort_values

(

by

=

'Word'

,

key

=

lambda

x: x.

str

.

lower

(

)

)

print

(

"Ascending alphabetical (case-insensitive):"

)

print

(

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:

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

)

print

(

"Original data:"

)

print

(

df

)

print

(

f

"Original data id: {id(df)}"

)

print

(

"="

50

)

Sort in place with inplace=True

df.

sort_values

(

by

=

'Score'

,

inplace

=

True

)

print

(

"After sorting with inplace=True:"

)

print

(

df

)

print

(

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:


Notes


Pandas Common Functions Common Pandas functions