python数据框架中的查询近似?

python数据框架中的查询近似?,python,dataframe,jupyter-notebook,Python,Dataframe,Jupyter Notebook,有没有办法在python数据帧中查询近似值? 因此,对于本例,我可能对Y列中的值感兴趣,该值与X列中的2最接近,该值应为“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'] }) 您可以按以下两个步骤执行此操作: query_value=2 # the v

有没有办法在python数据帧中查询近似值?
因此,对于本例,我可能对
Y
列中的值感兴趣,该值与
X
列中的
2
最接近,该值应为“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']
})

您可以按以下两个步骤执行此操作:

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']

您可以按以下两个步骤执行此操作:

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']

查询范围也可能非常有用!我投票决定重新讨论这个问题,因为我想我知道这个问题的意图,并且已经试图让这个问题更清楚。查询一个范围也会非常有帮助!我投票赞成重新讨论这个问题,因为我想我知道这个问题的意图是什么,并且已经试图使这个问题更清楚。