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

如何在Python中使用For Loop修改Pandas DataFrame变量中的数值

实现方案

你可以直接通过遍历DataFrame的索引或者行完成需求,完整代码如下:

步骤1:导入依赖、构造测试数据

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'id': [0, 1, 2, 3, 4],
    'target': [0.5595, 0.9642, 0.6225, 0.1256, 0.1966]
})

步骤2:通过For Loop修改target列值

方法1:遍历索引修改(代码更简洁)

for i in df.index:
    if df.loc[i, 'target'] > 0.5:
        df.loc[i, 'target'] += 0.2

方法2:用iterrows()逐行遍历修改

for index, row in df.iterrows():
    if row['target'] > 0.5:
        df.loc[index, 'target'] = row['target'] + 0.2

运行结果

修改完成后,target列的最终值如下:

0    0.7595
1    1.1642
2    0.8225
3    0.1256
4    0.1966

注意:如果数据量较大,更推荐用Pandas向量化操作df.loc[df['target']>0.5, 'target'] += 0.2,性能远高于For Loop,此处仅按要求提供For Loop实现方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:12:03