12.4: Sorting Serieses

The Crystal Ball - Instruction Manual I: Introduction to Data Science · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    12.4: Sorting Serieses

    Sorting is slightly more complex than for arrays, since there are two things we might want to sort by: the Series’ index, or the values themselves. Correspondingly, there are two methods: .sort_index() and .sort_values():

    Code \(\PageIndex{1}\) (Python):

    print(anti_vamps.sort_index())

    | Buffy 120

    | Rubert 150

    | Willow 200

    | Xander 72

    | dtype: int64

    Code \(\PageIndex{2}\) (Python):

    print(anti_vamps.sort_values())

    | Xander 72

    | Buffy 120

    | Rubert 150

    | Willow 200

    | dtype: int64

    Like NumPy’s np.sort() function (but unlike its .sort() method; refer back to Section 9.5), neither of these methods actually sort the Series in place; instead, they return sorted copies. However, they can be made to work in place, by including “inplace=True” as an argument:

    Code \(\PageIndex{3}\) (Python):

    heroes_dumb_to_smart = anti_vamps.sort_values()

    print(heroes_dumb_to_smart)

    | Xander 72

    | Buffy 120

    | Rubert 150

    | Willow 200

    | dtype: int64

    Code \(\PageIndex{4}\) (Python):

    print(anti_vamps)

    | Buffy 120

    | Xander 72

    | Willow 200

    | Rubert 150

    | dtype: int64

    Code \(\PageIndex{5}\) (Python):

    anti_vamps.sort_values(inplace=True)

    print(anti_vamps)

    | Xander 72

    | Buffy 120

    | Rubert 150

    | Willow 200

    | dtype: int64

    Another useful feature of both .sort_X methods is the ability to reverse sort. By adding “ascending=False” as an argument (with or without also including the “inplace=True” argument; they are combinable with a comma) you produce the reverse order:

    Code \(\PageIndex{6}\) (Python):

    heroes_smart_to_dumb = anti_vamps.sort_values(ascending=False)

    print(heroes_smart_to_dumb)

    | Willow 200

    | Rubert 150

    | Buffy 120

    | Xander 72

    | dtype: int64

    Code \(\PageIndex{7}\) (Python):

    anti_vamps.sort_index(inplace=True, ascending=False)

    print(anti_vamps)

    | Xander 72

    | Willow 200

    | Rubert 150

    | Buffy 120

    | dtype: int64


    This page titled 12.4: Sorting Serieses was last modified on Sun, 18 Sep 2022 02:06:14 GMT and is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform.