You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选Pandas DataFrame中与输入数值接近的所有行

如何输出DataFrame中与输入数值接近的所有行?

给出的样例数据集代码如下:

import pandas as pd

data = {'A':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        'B':[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]}

df = pd.DataFrame(data, columns=['A', 'B'])

你需要的nearest_values函数可以基于差值绝对值判断逻辑实现,默认差值阈值设为2,也支持自定义调整阈值:

def nearest_values(df, target_a, target_b, threshold=2):
    # 筛选同时满足A列、B列和对应目标值差值在阈值范围内的行
    filter_mask = (abs(df['A'] - target_a) <= threshold) & (abs(df['B'] - target_b) <= threshold)
    return df[filter_mask]

调用测试:

print(nearest_values(df, 5, 15))

输出结果和要求完全一致:

AB
313
414
515
616
717

内容的提问来源于stack exchange,提问作者RDTJr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 17:45:06