user6162407
user6162407

Reputation: 267

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.

Upvotes: 3

Views: 80

Answers (1)

Stefan
Stefan

Reputation: 42885

Instead of .searchsorted() you could also check for the index of the pd.Series value that minimizes the absolute difference to the value in question:

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

Upvotes: 4

Related Questions