.sort_values()
Published Feb 10, 2023
Contribute to Docs
The .sort_values()
function sorts values in a DataFrame
along the selected axis and returns a DataFrame
with sorted values or None.
Syntax
dataframevalue.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
.sort_values()
uses the following parameters:
by
: A label or a list of labels to sort by (levels can also be specified if applicable).axis
: Specify which axis will be sorted (0 or index, 1 or columns), it defaults to 0.ascending
: Specify whether the sort will be ascending or descending (True
orFalse
), it defaults toTrue
.inplace
: By setting it toTrue
, the operation will be performed on the originalDataFrame
and the function will return None, it defaults toFalse
.kind
: Choose which algorithm to use: ‘quicksort’, ‘mergesort’, ‘heapsort’, or ‘stable’, it defaults toquicksort
. For more information click here.na_position
: Specify where to put theNaN
values, it defaults tolast
.ignore_index
: Ignore the original index and put a new ascending set of values in its place. The default isFalse
.key
: Apply a function before sorting.
Example
In the example below a DataFrame is created and sorted in multiple ways by applying the .sort_values()
method and altering the parameters passed.
# Import pandas and numpyimport pandas as pdimport numpy as np# Create the DataFramedf = pd.DataFrame({'numbers': [2, 2, 5, 9, np.nan, 1],'letters': ['D', 'A', 'B', 'Z', np.nan, 'C']})# Sort by the column 'numbers'print(df.sort_values(by=['numbers']), end='\n\n')# Sort by the columns 'numbers' and 'letters'print(df.sort_values(by=['numbers', 'letters']), end='\n\n')# Sort by the column 'numbers' and put NaN values firstprint(df.sort_values(by=['numbers'], na_position='first'), end='\n\n')
The output will look like this:
numbers letters5 1.0 C0 2.0 D1 2.0 A2 5.0 B3 9.0 Z4 NaN NaNnumbers letters5 1.0 C1 2.0 A0 2.0 D2 5.0 B3 9.0 Z4 NaN NaNnumbers letters4 NaN NaN5 1.0 C0 2.0 D1 2.0 A2 5.0 B3 9.0 Z
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours