DonQuixote
DonQuixote

Reputation: 451

Working With Series in Reverse Order (Latest First)

How can I reverse sort order of DataSeries in Pandas so that I'm working with them in descending order?

Upvotes: 8

Views: 15230

Answers (2)

Bernat
Bernat

Reputation: 123

I'm going to suggest some changes to the answer by @Wouter Overmeire:

In []: s = pd.Series([20, 10, 30], ['c', 'a', 'b'])
In []: s
Out[]:
c    20
a    10
b    30
dtype: int64

The pandas.Series.sort() method is deprecated in Pandas 0.18.1 but now pandas.Series.sort_values() can be used instead for (inplace or not) sorting.

s.sort_values()

The sort_values method has keywords to change to ascending or descending order: ascending=True, or to not sort inplace: inplace=False.

and the last line of code of the previous answer is not for sorting by values but to return a slice of the Series s starting from the bottom. The slicing method works as follows:

s[start:end:step]

In the previous answer's example the slice starts from the begining (start position left empty), ends at the end (end left empty) and it takes every value (step with absolute value 1) but starts from the bottom of the Series (step with minus sign "-")

In[]: s[::-1]
Out[]:
b    30
a    10
c    20
dtype: int64

Upvotes: 3

Wouter Overmeire
Wouter Overmeire

Reputation: 69136

In [28]: s = pd.Series([20, 10, 30], ['c', 'a', 'b'])

In [29]: s
Out[29]:
c    20
a    10
b    30
dtype: int64

Sorting on the index

In [30]: s.sort_index(ascending=False)
Out[30]:
c    20
b    30
a    10
dtype: int64

sorting on the values

In [31]: s.sort()

In [32]: s[::-1]
Out[32]:
b    30
c    20
a    10
dtype: int64

Upvotes: 17

Related Questions