user6162407 user6162407 - 5 months ago 11
Python Question

Nearest value of a given value

Given this pandas Series.

x = pd.Series([5, 10])


I use searchsorted and a loop to find the closest value of the looped number, X.

for X in xrange(1, 11):
print X, x.searchsorted(X)


What is returned.

1 [0]
2 [0]
3 [0]
4 [0]
5 [0]
6 [1]
7 [1]
8 [1]
9 [1]
10 [1]


What I'm trying to achieve is having 6 and 7 return
[0]
because those numbers are closer to 5 than 10.

Answer

Instead of .searchsorted() you could also:

import numpy as np
for X in range(1, 11):
    print(X, (np.abs(x - X)).argmin())

1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 1
9 1
10 1