How to get the index of ith item in pandas.Series or pandas.DataFrame?

前端 未结 1 1523
谎友^
谎友^ 2020-12-14 07:51

I\'m trying to get the index of 6th item in a Series I have.

This is how the head looks like:

United States    1.536434e+13
China                  


        
相关标签:
1条回答
  • 2020-12-14 08:12

    You could get it straight from the index

    s.index[5]
    

    Or

    s.index.values[5]
    

    It all depends on what you consider better. I can tell you that a numpy approach will probably be faster.

    For example. numpy.argsort returns an array where the first element in the array is the position in the array being sorted that should be first. The second element in argsort's return array is the position of the element in the array being sorted that should be second. So on and so forth.

    So you could do this to get the index value of the 6th item after being sorted.

    s.index.values[s.values.argsort()[5]]
    

    Or more transparently

    s.sort_values().index[5]
    

    Or more creatively

    s.nsmallest(6).idxmax()
    
    0 讨论(0)
提交回复
热议问题