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

如何基于指定min和max阈值对DataFrame进行过滤与值替换?

Pandas 实现方案

完整代码

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'Calls': ['R', 'A', 'S', 'S', 'Q', 'W', 'E'],
    'Weight': [1, 1, 3, 3, 7, 5, 9]
})

min_thresh = 3
max_thresh = 5

# 1. 过滤Weight小于3的行
df = df[df['Weight'] >= min_thresh]
# 2. 把大于5的Weight值统一替换为5
df['Weight'] = df['Weight'].clip(upper=max_thresh)

# 输出结果
print(df)

代码说明

  • 行过滤用布尔索引直接筛选符合Weight >= min_thresh的记录,逻辑清晰易读
  • clip(upper=max_thresh)是pandas内置的数值钳位方法,自动将所有超过上限的数值替换为阈值,无需手动写循环或条件判断,执行效率更高。如果你更习惯显式赋值的写法,也可以用下面的代码替换第二步:
df.loc[df['Weight'] > max_thresh, 'Weight'] = max_thresh

运行输出

Calls  Weight
2     S       3
3     S       3
4     Q       5
5     W       5
6     E       5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:21:03