How do I find the closest values in a Pandas series to an input number?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I find the closest values in a Pandas series to an input number in Python. So Here I am Explain to you all the possible Methods here.

How do I find the closest values in a Pandas series to an input number?

1. How do I find the closest values in a Pandas series to an input number?

I recommend using iloc in addition to John Galt's answer since this will work even with unsorted integer index, since .ix first looks at the index labels

2. find the closest values in a Pandas series to an input number

I recommend using iloc in addition to John Galt's answer since this will work even with unsorted integer index, since .ix first looks at the index labels

Method 1

You could use argsort() like

Say, input = 3

In : input = 3

In : df.iloc[(df['num']-input).abs().argsort()[:2]]
Out:
num
2    4
4    2

df_sort is the dataframe with 2 closest values.

In : df_sort = df.iloc[(df['num']-input).abs().argsort()[:2]]

For index,

In : df_sort.index.tolist()
Out: [2, 4]

For values,

In : df_sort['num'].tolist()
Out: [4, 2]

Detail, for the above solution df was

In : df
Out:
num
0    1
1    6
2    4
3    5
4    2

Method 2

I recommend using iloc in addition to John Galt’s answer since this will work even with unsorted integer index, since .ix first looks at the index labels

df.iloc[(df['num']-input).abs().argsort()[:2]]

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.