首页 > 解决方案 > 在 python 数据框中查询近似值?

问题描述

有没有办法在 python 数据框中查询近似值?
所以对于这个例子,我可能对列Y中的值最接近2列中的值感兴趣,X这应该给我“f”和/或“w”。请参见下面的示例:

df = pd.DataFrame({  
'X': [1,3,4,6,8,12,15,23,22,32],  
'Y': ['f', 'w', 'fsssa', 'ddf', 'wq', 'h', 'wss', 'rrh', 'ddw', 'e4']
})

标签: pythondataframejupyter-notebook

解决方案


您可以分两步执行此操作,如下所示:

query_value=2 # the value, you want to query for
# calculate the absolute distance to the query value
ser_abs= (df['X']-query_value).abs()
# filter the rows for the rows with the minimum distance
df[ser_abs == ser_abs.min()]

这评估为:

   X  Y
0  1  f
1  3  w

如果您只对 Y 值感兴趣,最后一行是:

df.loc[ser_abs == ser_abs.min(), 'Y']

推荐阅读