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

如何将Pandas DataFrame指定列的数值裁剪到给定范围?

实现方案

你可以直接使用pandas内置的clip()方法完成数值区间裁剪,这个方法的逻辑就是:小于下界的值赋值为下界,大于上界的值赋值为上界,区间内的值保持不变,完全匹配你的需求。

核心操作只需要1行代码,选中需要处理的3列,指定上下界为-1和1即可:

df[['c1', 'c2', 'c3']] = df[['c1', 'c2', 'c3']].clip(lower=-1, upper=1)

把这行代码加到你原有测试代码的print逻辑前,完整测试代码如下:

import numpy as np
import pandas as pd

rand = np.random.default_rng(seed=0)
df = pd.DataFrame(rand.uniform(-2, 2, 50).reshape(10, 5), columns=['a', 'b', 'c1', 'c2', 'c3'])

# 裁剪指定列到[-1, 1]区间
df[['c1', 'c2', 'c3']] = df[['c1', 'c2', 'c3']].clip(lower=-1, upper=1)

print(df)

运行后输出的结果和你给出的预期结果完全一致:

a         b        c1        c2        c3
0  0.547847 -0.920853 -1.000000 -1.000000  1.000000
1  1.651022  0.426543  0.917986  0.174500  1.000000
2  1.263414 -1.989046  1.000000 -1.000000  0.918622
3 -1.297378  1.452716  0.165845 -0.801152 -0.309251
4 -1.886721 -1.502867  0.682498  0.588758  0.461540
5 -0.465290  1.988840  1.000000  0.742168  0.601837
6  0.753787 -0.444314 -1.000000  0.885953  0.101417
7 -0.759032 -0.056659  1.000000  1.000000 -0.568819
8  0.286119 -0.712522  0.377200 -0.648355 -0.433524
9  1.561097 -1.091370  0.492749 -1.000000  1.000000

注:你给出的预期结果里截断后的数值显示省略了末尾的0,是pandas打印时的显示格式差异,实际数值完全相等,如果需要调整显示格式可以通过pd.set_option设置浮点数显示精度,不影响实际计算结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 03:01:17