Located closest value in pandas dataframe

61 views Asked by At

I'm trying to located the closest value in a dataframe with user input.

Key  col1       col2
10   300        140
12   450        165
15   650        890
20   130        900
25   110        755

let's say i'm trying to input value 16. the value pandas should generate is

Key  col1   col2
15   650    890

I tried the df.loc, but that only works for specific values that are in the dataframe i guess.

Does anybody have an idea how i can fix this?

2

There are 2 answers

0
jezrael On

Use Series.idxmin with absolute values after subtract value:

val = 16
df = df.loc[[(df['Key'] - val).abs().idxmin()]]
print (df)
   Key  col1  col2
2   15   650   890
0
BENY On

IIUC reindex nearest

df=df.set_index(['Key']).reindex([16],method = 'nearest').reset_index()

     col1  col2
Key            
16    650   890