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

如何将一个DataFrame的指定列合并到另一个DataFrame并插入到指定位置?

Hey there! Let's walk through your two Pandas questions with clear, actionable steps and code examples tailored to your specific scenario.

问题1:将一个DataFrame中的某些列合并到另一个DataFrame中

There are two common scenarios here, depending on how your data is aligned:

场景1:两个DataFrame的行完全对齐(索引一致)

If your df1 and df2 have the same number of rows and matching indexes (each row in df1 corresponds directly to the same row in df2), you have two simple options:

方法1:使用pd.concat

This lets you stitch columns together along the horizontal axis (axis=1):

import pandas as pd

# 读取你的CSV文件
df1 = pd.read_csv('df1.csv')
df2 = pd.read_csv('df2.csv')

# 只选择df1中需要的列合并到df2
df_combined = pd.concat([df2, df1[['C', 'D']]], axis=1)

方法2:直接赋值列

You can also assign columns from df1 directly to df2:

df2['C'] = df1['C']
df2['D'] = df1['D']

场景2:基于共同键合并(行不完全对齐)

If your rows don't match by index but share a common identifier (like an id column), use pd.merge to ensure rows are correctly matched:

# 假设两表都有一个用于匹配的'id'列
df_combined = pd.merge(df2, df1[['id', 'C', 'D']], on='id', how='left')
# `how='left'`确保保留df2的所有行,即使df1中没有对应匹配项
问题2:在指定位置插入列到DataFrame

Your specific scenario requires inserting df1's C and D columns right after df2's B column. Let's break this down step by step:

Step 1: 准备数据(模拟读取后的状态)

First, let's replicate your DataFrames to test with:

import pandas as pd

df1 = pd.DataFrame({'C': [1,2,3], 'D': [4,5,6], 'E': [7,8,9]})
df2 = pd.DataFrame({'K': ['x','y','z'], 'L': ['a','b','c'], 'A': [10,11,12], 'B': [13,14,15], 'F': [16,17,18]})

Step 2: 确定插入位置

Find the index of the column you want to insert after (B), then calculate the insertion position:

# 获取df2的列名列表
columns = list(df2.columns)
# 找到'B'列的索引,插入位置是该索引+1(放在B的后面)
insert_position = columns.index('B') + 1

Step 3: 构造新的列顺序

Build the desired column order by inserting C and D into the correct spot:

new_column_order = columns[:insert_position] + ['C', 'D'] + columns[insert_position:]

Step 4: 合并列并重新排序

First, add the C and D columns to df2 (assuming rows are aligned), then reorder the columns to match your desired sequence:

# 合并df2和需要的列
df_with_cd = pd.concat([df2, df1[['C', 'D']]], axis=1)
# 按新顺序重新排列列
df3 = df_with_cd[new_column_order]

After running this, df3.columns will be exactly ['K','L','A','B','C','D','F'] as you requested!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:24:11