Reputation: 181
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?
Upvotes: 0
Views: 61
Reputation: 862406
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
Upvotes: 2
Reputation: 323226
IIUC reindex
nearest
df=df.set_index(['Key']).reindex([16],method = 'nearest').reset_index()
col1 col2
Key
16 650 890
Upvotes: 1