Leon
Leon

Reputation: 2077

How to use Pandas.sort_index() and pd.index.searchsorted()?

I need to sort a Dataframe/Series along the Index, and then use searchsorted to find out the iloc of a target value, so as to do a slice.

If I do sort_index(ascending=True), I can get the results what I want. But I can't get it work when I sort it Descending.

For example:

>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4])
>>> s.sort_index(ascending=True, inplace=True)
>>> s
1    c
2    b
3    a
4    d
dtype: object
>>> s.index.searchsorted( 1 )
0    # search in a ascending sorted Series, it works.
>>> s.index.searchsorted( 2 )
1    # search in a ascending sorted Series, it works.
>>> s.index.searchsorted( 3 )
2    # search in a ascending sorted Series, it works.
>>> s.index.searchsorted( 4 )
3    # search in a ascending sorted Series, it works.

If I sort it descending, I can NOT get the results what I want:

>>> s.sort_index(ascending=False, inplace=True)
>>> s.index.searchsorted( 1 )
0    # search in a descending sorted Series, it doesnt' work!
>>> s.index.searchsorted( 2 )
0    # search in a descending sorted Series, it doesnt' work!
>>> s.index.searchsorted( 3 )
4    # search in a descending sorted Series, it doesnt' work!
>>> s.index.searchsorted( 4 )
4    # search in a descending sorted Series, it doesnt' work!

How to sort it descending? Thanks!

Upvotes: 0

Views: 28

Answers (0)

Related Questions