Add function to find index closest to a val in df

This commit is contained in:
rasmusthog 2022-10-15 17:14:31 +02:00
parent 82b0981ada
commit 8775a20ba5

View file

@ -164,3 +164,24 @@ def swap_values(options: dict, key1, key2):
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]