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

如何在Pandas DataFrame的第2行插入指定列表数据?

在Pandas DataFrame指定位置插入行的方法

你提到的insert方法确实只能插入列,要在指定位置插入行,可以用以下几种方法:

方法1:拆分原表后拼接(推荐)

将原DataFrame拆分为插入位置前、插入位置后的两部分,再和转成DataFrame的目标列表拼接:

import pandas as pd
dat = pd.DataFrame({'A': [1,2,3,5], 'B': [7,6,7,8]})
List = [99, 88]

# 将列表转为与原表列名一致的单行DataFrame
new_row = pd.DataFrame([List], columns=dat.columns)
# 拆分原表并拼接,最后重置索引避免重复
dat = pd.concat([dat.iloc[:1], new_row, dat.iloc[1:]]).reset_index(drop=True)
print(dat)

输出结果:

A   B
0   1   7
1  99  88
2   2   6
3   3   7
4   5   8

注:这里iloc[:1]取原表第1行(索引0),iloc[1:]取原表从第2行开始的所有行,对应你要插入到第2行的需求。

方法2:修改索引腾出位置插入

通过调整原表索引,为新行腾出位置后赋值:

import pandas as pd
dat = pd.DataFrame({'A': [1,2,3,5], 'B': [7,6,7,8]})
List = [99, 88]

insert_pos = 1  # 对应第2行(0-based索引)
# 原表中索引大于等于insert_pos的行,索引加1,腾出位置
dat.index = dat.index.where(dat.index < insert_pos, dat.index + 1)
# 插入新行
dat.loc[insert_pos] = List
# 排序索引并重置
dat = dat.sort_index().reset_index(drop=True)
print(dat)

方法3:append结合reindex(注意版本兼容)

如果使用Pandas 2.0以下版本,也可以用append,但该方法已被弃用,不推荐在新版本中使用:

import pandas as pd
dat = pd.DataFrame({'A': [1,2,3,5], 'B': [7,6,7,8]})
List = [99, 88]

insert_pos = 1
# 生成包含插入位置的新索引
new_index = list(range(insert_pos)) + [insert_pos] + list(range(insert_pos, len(dat)))
# 添加新行并按新索引排序
dat = dat.append(pd.Series(List, index=dat.columns), ignore_index=False)
dat = dat.reindex(new_index).reset_index(drop=True)
print(dat)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:07:12