From 8775a20ba549824ae0c929d1113895030d5f4719 Mon Sep 17 00:00:00 2001 From: rasmusthog Date: Sat, 15 Oct 2022 17:14:31 +0200 Subject: [PATCH] Add function to find index closest to a val in df --- nafuma/auxillary.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/nafuma/auxillary.py b/nafuma/auxillary.py index 8044914..c01940c 100644 --- a/nafuma/auxillary.py +++ b/nafuma/auxillary.py @@ -163,4 +163,25 @@ def swap_values(options: dict, key1, key2): options[k1], options[k2] = options[k2], options[k1] - return options \ No newline at end of file + return options + + + +def find_neighbours(value, df, colname, start=0, end=-1): + ''' Finds closest match to a given value in colname of df. If there is an exact match, returns index of this value. Else, it returns the nearest neighbors (upper and lower)''' + + df = df.iloc[start:end] + + exactmatch = df[df[colname] == value] + if not exactmatch.empty: + return exactmatch.index + else: + lower_df = df[df[colname] < value][colname] + upper_df = df[df[colname] > value][colname] + + lowerneighbour_ind = lower_df.idxmax() + upperneighbour_ind = upper_df.idxmin() + + print(lowerneighbour_ind, upperneighbour_ind) + + return [lowerneighbour_ind, upperneighbour_ind] \ No newline at end of file