I have seen:
These relate to vanilla python and not pandas.
If I have the series:
ix num
0 1
1 6
2 4
3 5
4 2
And I input 3, how can I (efficiently) find?
Ie. With the above series {1,6,4,5,2}, and input 3, I should get values (4,2) with indexes (2,4).
You could use argsort()
like
Say, input = 3
In [198]: input = 3
In [199]: df.iloc[(df['num']-input).abs().argsort()[:2]]
Out[199]:
num
2 4
4 2
df_sort
is the dataframe with 2 closest values.
In [200]: df_sort = df.iloc[(df['num']-input).abs().argsort()[:2]]
For index,
In [201]: df_sort.index.tolist()
Out[201]: [2, 4]
For values,
In [202]: df_sort['num'].tolist()
Out[202]: [4, 2]
Detail, for the above solution df
was
In [197]: df
Out[197]:
num
0 1
1 6
2 4
3 5
4 2