Python 如何获取pandas.Series中第i个项目的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41273005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get the index of ith item in pandas.Series
提问by D3VLPR
I'm trying to get the index of 6th item in the Series I have.
我正在尝试获取我拥有的系列中第 6 项的索引。
This is how the head looks like
这是头部的样子
United States 1.536434e+13
China 6.348609e+12
Japan 5.542208e+12
Germany 3.493025e+12
France 2.681725e+12
For getting the 6th index name ( 6th Country after being sorted ), I usually use s.head(6) and get the 6th index from there
为了获取第 6 个索引名称(排序后的第 6 个国家/地区),我通常使用 s.head(6) 并从那里获取第 6 个索引
s.head(6) gives me
s.head(6) 给了我
United States 1.536434e+13
China 6.348609e+12
Japan 5.542208e+12
Germany 3.493025e+12
France 2.681725e+12
United Kingdom 2.487907e+12
and looking at this, I'm getting the index as United Kingdom.
看看这个,我得到的索引是英国。
So, is there any better way for getting the index other than this. And also, for a data frame, is there any function to get the 6th index on basis of a respective column after sorting.
那么,除此之外,还有没有更好的方法来获取索引。而且,对于数据框,是否有任何函数可以在排序后根据相应的列获取第 6 个索引。
If it's data frame, I usually, sort, create a new column named index, and use reset_index and then use iloc attribute to get the 6th ( Since, it will be using an range in the index after reset ).
如果是数据框,我通常会排序,创建一个名为 index 的新列,然后使用 reset_index ,然后使用 iloc 属性获取第 6 个(因为,它将在 reset 后使用索引中的范围)。
Is there any better way in doing this with pd.Series and pd.DataFrame.
有没有更好的方法来使用 pd.Series 和 pd.DataFrame 做到这一点。
Thank you.
谢谢你。
回答by piRSquared
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.
这完全取决于您的考虑better
。我可以告诉你,一种numpy
方法可能会更快。
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.
例如。 numpy.argsort
返回一个数组,其中数组中的第一个元素是要排序的数组中应该排在第一位的位置。argsort 返回数组中的第二个元素是要排序的数组中应该是第二个元素的位置。等等等等。
So you could do this to get the index value of the 6th item after being sorted.
因此,您可以这样做以获取排序后的第 6 个项目的索引值。
s.index.values[s.values.argsort()[5]]
Or more transparently
或者更透明
s.sort_values().index[5]
Or more creatively
或者更有创意
s.nsmallest(6).idxmax()
回答by davidbilla
s.index[5] should give you the index of the 6th item
s.index[5] 应该给你第 6 项的索引