12.4: Sorting Serieses
- Page ID
- 39281
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