Why calling .sort() function on Pandas Series sorts its values in-place and returns nothing?

.sort() sorts in-place.

That means that after you call .sort(), your existing array has been sorted. It doesn't return anything.

To take an example from "core" Python:

In [175]: L = [2, 3, 1, 5]

In [176]: L.sort()

In [177]: print(L)
[1, 2, 3, 5]

It's the same for Pandas, as documented by Pandas.sort:

Sort values and index labels by value, in place. For compatibility with ndarray API. No return value

See also: What's the difference between Series.sort() and Series.order()?


In [1]: import pandas as pd
In [2]: s = pd.Series([3,4,0,3]).sort()
In [3]: s

Indeed In [3] will output nothing, as you can check:

In [4]: type(s)
Out[4]: NoneType

The reason:

pd.Series([3,4,0,3]) indeed return a pandas Series type object, BUT Series.sort() method return nothing because of inplace sorting. So the expression s = pd.Series([3,4,0,3]).sort(), s in LHS get nothing from RHS, thus In [3]: s output nothing.

NOTE that:

After version 0.17.0, sorting by value methods pandas.Series.sort() and pandas.Series.order() are DEPRECATED, replaced by a unified pandas.Series.sort_values() API. See this answer for more details.


Both .sort() and order() functions are DEPRECATED

.sort_values() function is the replacement and here's the example on how to use it.

Example:

import numpy as np
import pandas as pd

arr = np.array([1,3,4,2])
series = pd.Series(arr)

Ascending Order
Equivalent to .order() function from old versions.

ascending = series.sort_values() 


Descending Order
Equivalent to .order(ascending=False)

descending = series.sort_values(ascending=False)


In Place
Equivalent to .sort() from old versions.

series.sort_values(inplace=True) 

For more info, check official documentation here