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

如何使用Pandas按条件在DataFrame任意位置插入指定行?

解决Pandas按条件插入行的问题

需求回顾

  • 遍历数据集每行,检查potveg列值是否为4、8或9
  • 满足条件时,在该行下方插入新行:
    • col、lat与原行保持一致
    • icohort、isrccohort设为原行值+1
    • 其余列按指定默认值填充(如standage=3000、potveg=13等)
  • 最终将更新后的数据集导出为CSV

原代码存在的问题

  1. 效率与弃用API:使用iterrows()遍历效率偏低,且df.append()已被Pandas官方弃用
  2. 逻辑错误:误用上一行(last_row)和当前行(next_row),新行应基于匹配的当前行创建
  3. 条件不全:仅判断了potveg==4,未覆盖8和9
  4. 插入位置错误:append会把新行加到数据集末尾,而非目标行的下方

修正后的代码

import pandas as pd

# 读取原始数据集(替换为你的文件路径)
df = pd.read_csv("your_input_data.csv")

# 存储待插入的行及其目标位置
insert_records = []

# 遍历每行检查条件
for idx, row in df.iterrows():
    if row["potveg"] in [4, 8, 9]:
        # 复制原行作为新行基础
        new_row = row.copy()
        # 设置指定列的值
        new_row["col"] = row["col"]
        new_row["lat"] = row["lat"]
        new_row["icohort"] = row["icohort"] + 1
        new_row["isrccohort"] = row["isrccohort"] + 1
        # 填充其他列的默认值
        new_row.update({
            "standage": 3000,
            "chrtarea": 0,
            "potveg": 13,
            "currentveg": 13,
            "subtype": 13,
            "agstate": 0,
            "agprevstate": 0,
            "tillflag": 0,
            "fertflag": 0,
            "irrgflag": 0,
            "disturbflag": 0,
            "disturbmonth": 0,
            "FRI": 2000,
            "slashpar": 0,
            "vconvert": 0,
            "prod10par": 0,
            "prod100par": 0,
            "vrespar": 0,
            "sconvert": 0
        })
        # 记录插入位置(原行索引+1)和新行数据
        insert_records.append((idx + 1, new_row))

# 倒序插入,避免插入后索引偏移影响后续位置
insert_records.sort(reverse=True)
for pos, row_data in insert_records:
    df = pd.concat(
        [df.iloc[:pos], pd.DataFrame([row_data]), df.iloc[pos:]],
        ignore_index=True
    )

# 导出更新后的数据集
df.to_csv("updated_output_data.csv", index=False)

代码说明

  • 使用row.copy()复制原行,避免修改原始数据
  • 用update()批量设置默认值,代码更简洁
  • 收集所有插入任务后倒序处理:先插入靠后的行,防止前面的插入操作导致后续位置偏移
  • 用pd.concat()替代append,符合Pandas最新的API规范,效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:15:27