如何基于指定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
相关产品推荐
相关产品推荐

