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

如何在Pandas DataFrame指定位置按需插入自定义新行?

解决方案

你的核心问题是直接修改索引位置的值会覆盖原有数据,而非插入新行。以下是实现需求的高效方法:

完整代码

import pandas as pd

# 读取数据(保留你的读取逻辑)
with open("week-1-algorithm.txt", "r") as f:
    text = [line.split() for line in f]

df = pd.DataFrame(text, columns=["Column1", "Column2"])

# 1. 标记所有新分组的起始行(Column1与上一行不同的行,包含第一行)
is_new_group = df["Column1"] != df["Column1"].shift()
new_group_indices = df[is_new_group].index

# 2. 生成需要插入的分隔行
insert_rows = pd.DataFrame({
    "Column1": [f"t # {i}" for i in range(len(new_group_indices))],
    "Column2": [pd.NA] * len(new_group_indices)
})
# 设置插入行的索引为原起始行索引减0.5,确保排序后在对应行上方
insert_rows.index = new_group_indices - 0.5

# 3. 合并原数据与插入行,排序后重置索引
combined_df = pd.concat([df, insert_rows]).sort_index().reset_index(drop=True)

# 查看结果
print(combined_df)

关键逻辑说明

  1. 识别分组起始行:用shift()对比当前行与上一行的Column1值,标记所有新分组的起始位置。
  2. 生成插入行:为每个起始行生成对应的t # {编号}行,Column2设为pd.NA(对应NULL)。
  3. 插入并排序:通过给插入行设置偏移索引(原索引-0.5),合并后排序即可让插入行自动出现在对应分组的上方,最后重置索引得到连续的行号。

原代码问题分析

你使用new_df.loc[i+1] = ...时,是直接修改已有索引位置的数值,而非插入新行。Pandas的索引是固定映射,直接赋值只会覆盖原有数据,无法实现插入操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:25