Access value by location in sorted pandas series with integer index

岁酱吖の 提交于 2019-12-05 15:23:56

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]

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