dataframe - How to use Pandas.sort_index() and pd.index.searchsorted()? - Stack Overflow

I need to sort a DataframeSeries along the Index, and then use searchsorted to find out the iloc of a

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 do 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 doesn't work!
>>> s.index.searchsorted( 2 )
0    # search in a descending sorted Series, it doesn't work!
>>> s.index.searchsorted( 3 )
4    # search in a descending sorted Series, it doesn't work!
>>> s.index.searchsorted( 4 )
4    # search in a descending sorted Series, it doesn't work!

How to sort it descending?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745067556a4609343.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信