python - 在 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']
})
解决方案
您可以分两步执行此操作,如下所示:
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']
推荐阅读
- python - apache_beam.examples.wordcount 的输入
- android - 在按钮单击时将事件添加到日历
- qt - 在 Ubuntu 中设置 ANDROID_NDK_PLATFORM
- reactjs - 移除元素时状态不更新
- javascript - 从nodejs应用程序使用二进制(golang)并使用输出
- firebase - Firebase 消息,未收到消息
- elasticsearch - Kibana/Elastic Query 对同一数组元素中的多个术语进行查询
- angular - 如何使用Angular 7在mat-select-trigger标签内显示选定的选项名称
- html - 遮盖一个对象,使它看起来好像它在它正在旋转的项目后面
- javascript - 获取下载 URL 并使其可用于其他组件