how to find the closest value in column python 1

how to find the closest value in column python

	result_index = df['col_to_search'].sub(search_value).abs().idxmin()

#.sub(search_value) subtracts search_value from the df[col_to_search] to make the nearest value almost-zero,
#.abs() makes the almost-zero the minimum of the column,
#.idxmin() yields the df.index of the minimum value, or the closest match to search_value.

Here is what the above code is Doing:
1. df[‘col_to_search’].sub(search_value)
– subtracts search_value from the df[col_to_search] to make the nearest value almost-zero
2. .abs()
– makes the almost-zero the minimum of the column
3. .idxmin()
– yields the df.index of the minimum value, or the closest match to search_value.

Similar Posts