Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access value by location in sorted pandas series with integer index

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?

like image 204
Jonas Avatar asked Dec 15 '22 15:12

Jonas


2 Answers

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]
like image 170
eumiro Avatar answered Dec 21 '22 09:12

eumiro


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
like image 20
Andy Hayden Avatar answered Dec 21 '22 11:12

Andy Hayden