-1

I have following DataFrame

    0
0   5
1   10
2   15
3   20

i want get location of value which is near to n value. For example: if n=7 then nearest number is 5 . And after this return location of 5 i.e [0] [0]

ClaWnN
  • 49
  • 7
  • What if there's more than on number that is equally close? Also, what if exactly the same? Also, what steps have you taken to solve this problem? – run-out May 03 '19 at 07:07
  • yes, if n=5, or 6. nearest number must be 5 – ClaWnN May 03 '19 at 07:09
  • 1
    Possible duplicate of [Find nearest value in numpy array](https://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array) – Chris May 03 '19 at 07:13
  • thanks, but what about returning location ? – ClaWnN May 03 '19 at 07:24

2 Answers2

1

Use Series.abs and Series.idxmin:

# Setup
df = pd.DataFrame({0: {0: 5, 1: 10, 2: 15, 3: 20}})
n = 7

(n - df[0]).abs().idxmin()

[out]

0
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
0

Use numpy.argmin to get the closest number index:

df[1] = 7
df[2] = df[1] - df[0]
df[2] = df[2].abs()
print(np.argmin(df[2]))
hacker315
  • 1,996
  • 2
  • 13
  • 23