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

Pandas拆分单元格字符串插入新行并扩展DataFrame不覆盖原有行如何实现

Pandas拆分符合条件的行、不覆盖原有数据的解决方案

不要直接在原DataFrame上通过loc/iloc/at赋值的方式插入新行,pandas的该类API仅支持修改已有索引对应的数据,不会自动将后续行后移扩容,所以会出现覆盖尾部数据的问题。
更简单高效的方式是先收集所有待保留的行数据,最后一次性生成新的DataFrame:

完整实现代码

import pandas as pd

# 此处替换为你自己的原始DataFrame即可
df = pd.DataFrame({
    "no": [1,2,3,4,5,6],
    "word": ["test1", "test2", "test3", '"future"', "test5", "test6"],
    "status": ["done", "done", "done", "to_check", "done", "done"]
})

processed_list = []
for _, row in df.iterrows():
    current_word = str(row["word"])
    # 校验当前行word是否首尾都带双引号
    if len(current_word) >= 2 and current_word.startswith('"') and current_word.endswith('"'):
        # 追加拆分后的3行数据
        processed_list.append({"no": row["no"], "word": '"', "status": "quotes"})
        processed_list.append({"no": row["no"], "word": current_word.strip('"'), "status": "word"})
        processed_list.append({"no": row["no"], "word": '"', "status": "quotes"})
    else:
        # 不符合拆分条件的行直接原样保留
        processed_list.append(row.to_dict())

# 生成最终的扩展DataFrame
new_df = pd.DataFrame(processed_list)

可选:指定位置插入行的通用方法

如果有明确要在某索引位置插入固定行数的需求,可以用pd.concat拼接拆分后的DataFrame片段:

# 示例:在原索引4的位置插入3行新数据
insert_rows = pd.DataFrame({
    "no": [4,4,4],
    "word": ['"', "future", '"'],
    "status": ["quotes", "word", "quotes"]
})
# 拼接原DF前4行、新插入行、原DF索引4之后的行
new_df = pd.concat([df.iloc[:4], insert_rows, df.iloc[5:]], ignore_index=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:45:04