Access value by location in sorted pandas series with integer index

只谈情不闲聊 提交于 2019-12-10 07:56:05

问题


I have a pandas Series with an integer index which I've sorted (by value), how I access values by position in this Series.

For example:

s_original = pd.Series({0: -0.000213, 1: 0.00031399999999999999, 2: -0.00024899999999999998, 3: -2.6999999999999999e-05, 4: 0.000122})
s_sorted = np.sort(s_original)

In [3]: s_original
Out[3]: 
0   -0.000213
1    0.000314
2   -0.000249
3   -0.000027
4    0.000122

In [4]: s_sorted
Out[4]: 
2   -0.000249
0   -0.000213
3   -0.000027
4    0.000122
1    0.000314

In [5]: s_sorted[3]
Out[5]: -2.6999999999999999e-05

But I would like to get the value 0.000122 i.e. the item in position 3.
How can I do this?


回答1:


Replace the line

b = np.sort(a)

with

b = pd.Series(np.sort(a), index=a.index)

This will sort the values, but keep the index.

EDIT:

To get the fourth value in the sorted Series:

np.sort(a).values[3]



回答2:


You can use iget to retrieve by position:
(In fact, this method was created especially to overcome this ambiguity.)

In [1]: s = pd.Series([0, 2, 1])

In [2]: s.sort()

In [3]: s
Out[3]: 
0    0
2    1
1    2

In [4]: s.iget(1)
Out[4]: 1

.

The behaviour of .ix with an integer index is noted in the pandas "gotchas":

In pandas, our general viewpoint is that labels matter more than integer locations. Therefore, with an integer axis index only label-based indexing is possible with the standard tools like .ix.

This deliberate decision was made to prevent ambiguities and subtle bugs (many users reported finding bugs when the API change was made to stop “falling back” on position-based indexing).

Note: this would work if you were using a non-integer index, where .ix is not ambiguous.

For example:

In [11]: s1 = pd.Series([0, 2, 1], list('abc'))

In [12]: s1
Out[12]: 
a    0
b    2
c    1

In [13]: s1.sort()

In [14]: s1
Out[14]: 
a    0
c    1
b    2

In [15]: s1.ix[1]
Out[15]: 1


来源:https://stackoverflow.com/questions/14455746/access-value-by-location-in-sorted-pandas-series-with-integer-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!