Finding the Two Values Nearest a Target in a DataFrame
Summary
The document describes a simple way to find the two entries in a numeric column that are closest to a chosen target. Calculate each entry’s absolute distance from the target, sort those distances, and use the indices of the two smallest values to retrieve the corresponding original rows.
This is a brute-force method suited to a list or column that can be sorted directly. The note gives no benchmark, implementation details, or discussion of ties, missing values, or larger datasets, so it does not compare this approach with alternatives for those cases.
Key ideas
- Compute the absolute difference between every column value and the target.
- Sort the differences and select the indices of the two smallest ones.
- Use those indices to retrieve the original values or rows.
- The document does not discuss performance or edge cases such as ties and missing data.
Tags
Full text
# Two Closest Numbers to a number X # Two Closest Numbers to a number X I have a dataframe with a list of numbers in column A in Python, and I would like to get the two closest numbers in this list to a specific number X. Does anyone know how to do this? ## Answer by ml-guy (score 1, accepted) https://quant.stackexchange.com/a/73960 A brute force way of doing this is to create a new Series that is `abs(A-X)`. You sort the new series and select the indices of the top two items, which can be used to reference the two rows in the original data frame.
Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.