Add function to find index closest to a val in df
This commit is contained in:
parent
82b0981ada
commit
8775a20ba5
1 changed files with 22 additions and 1 deletions
|
|
@ -163,4 +163,25 @@ def swap_values(options: dict, key1, key2):
|
||||||
options[k1], options[k2] = options[k2], options[k1]
|
options[k1], options[k2] = options[k2], options[k1]
|
||||||
|
|
||||||
|
|
||||||
return options
|
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]
|
||||||
Loading…
Add table
Add a link
Reference in a new issue