位于熊猫数据框中最接近的值



我正在尝试使用用户输入在数据帧中找到最接近的值。

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

假设我正在尝试输入值 16。 熊猫应该生成的值是

Key  col1   col2
15   650    890

我尝试了df.loc,但这仅适用于我猜的数据框中的特定值。

有人知道我该如何解决这个问题吗?

在减去值后使用绝对值Series.idxmin

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

IIUCreindexnearest

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

最新更新