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

如何在DataFrame列间插入新列?含多列插入实例

Insert Multiple New Columns Between Existing Columns in a Pandas DataFrame

Got it, let's work through how to insert those month date columns into your DataFrame exactly where you need them. Here's a step-by-step solution that matches your desired output perfectly:

Step 1: Recreate the Input DataFrame

First, let's set up your starting DataFrame. Note that pandas automatically adds suffixes (like .1) to duplicate column names such as BL and RL:

import pandas as pd

data = {
    'PC': ['A', 'B'],
    'GEO': ['USA', 'IND'],
    'BL': [1, 1],
    'RL': [1, 1],
    'JanTOTAL': [2, 2],
    'BL': [1, 1],
    'RL': [1, 1],
    'FebTOTAL': [2, 2]
}
df = pd.DataFrame(data)

Step 2: Add the New Month Date Columns

Create the new date columns with your fixed date values:

df['Jan-Month'] = '2019-01-01'
df['Feb-Month'] = '2019-02-01'

Step 3: Insert Columns at the Correct Positions

We'll use pop() to temporarily remove the new columns, then insert() to place them right before their corresponding *TOTAL columns:

# Insert Jan-Month immediately before JanTOTAL
jan_total_position = df.columns.get_loc('JanTOTAL')
df.insert(jan_total_position, 'Jan-Month', df.pop('Jan-Month'))

# Insert Feb-Month immediately before FebTOTAL (note: positions shifted after first insert)
feb_total_position = df.columns.get_loc('FebTOTAL')
df.insert(feb_total_position, 'Feb-Month', df.pop('Feb-Month'))

Step 4: Fix Column Names and Final Order

Since pandas added suffixes to duplicate columns, we'll rename them back to match your desired output and lock in the correct column order:

# Define the exact column order you want
final_columns = ['PC', 'GEO', 'Jan-Month', 'BL', 'RL', 'JanTOTAL', 'Feb-Month', 'BL', 'RL', 'FebTOTAL']

# Reorder columns and map the suffixed duplicate columns to their original names
df = df[['PC', 'GEO', 'Jan-Month', 'BL', 'RL', 'JanTOTAL', 'Feb-Month', 'BL.1', 'RL.1', 'FebTOTAL']]
df.columns = final_columns

Final Result

When you print df, you'll get exactly the output you're looking for:

PC  GEO  Jan-Month  BL  RL  JanTOTAL  Feb-Month  BL  RL  FebTOTAL
0  A  USA 2019-01-01   1   1         2 2019-02-01   1   1         2
1  B  IND 2019-01-01   1   1         2 2019-02-01   1   1         2

Quick Note

While duplicate column names aren't ideal for long-term pandas work (they can cause confusion when querying or modifying data), this solution strictly adheres to your specified requirements. If you have more months to add later, you can wrap the insert logic in a loop to avoid repeating code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:04:58