You need to enable JavaScript to run this app. Pandas如何将DataFrame的多列批量插入另一个DataFrame的指定位置
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何将DataFrame的多列批量插入另一个DataFrame的指定位置

方法1:拆分拼接法(推荐,无需修改原df,适合多列插入)

通过pd.concat按位置拼接三个部分实现一次性插入多列,不需要逐列操作:

import pandas as pd

# 读取测试数据
df1 = pd.DataFrame.from_dict({
    'A': {0: 1, 1: 2, 2: 3, 3: 4},
    'B': {0: 5, 1: 6, 2: 7, 3: 8},
    'C': {0: 9, 1: 8, 2: 7, 3: 6}
})
df2 = pd.DataFrame.from_dict({
    'D': {0: 1, 1: 2, 2: 3, 3: 4},
    'E': {0: 5, 1: 6, 2: 7, 3: 8},
    'F': {0: 9, 1: 8, 2: 7, 3: 6}
})

# 计算插入位置:B列的下一个位置
insert_pos = df1.columns.get_loc('B') + 1
# 提取需要插入的列
need_insert = df2[['D', 'E']]
# 拆分原df1为插入位置前后两部分,和待插入列拼接
df_result = pd.concat([
    df1.iloc[:, :insert_pos],
    need_insert,
    df1.iloc[:, insert_pos:]
], axis=1)

输出df_result即可得到目标格式的DataFrame。


方法2:批量循环插入(适合需要直接修改原df的场景)

如果允许修改原df1,只需要定义好待插入的列列表,一次循环就能完成,列数再多也不需要手动写多次insert:

# 定义待插入列,列数多时直接修改这个列表即可
insert_cols = ['D', 'E']
start_pos = df1.columns.get_loc('B') + 1
for i, col in enumerate(insert_cols):
    df1.insert(start_pos + i, col, df2[col])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:42:03