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

如何用Pandas在DataFrame中创建内容相同但列名不同的重复列

Pandas批量生成内容相同、列名不同的重复列解决方案

你需要给DataFrame中指定列创建多个内容一致但列名不同的重复列,且重复列需紧跟原列之后。当前代码仅支持单列重复、未设置新列名且列顺序不符合预期,以下是修正方案:

原始数据构造

先构造可复现的原始DataFrame:

import pandas as pd

data = {
    'ID': ['AA', 'AA', 'BB', 'CC'],
    'type': ['all', 'ok', 'yes', 'maybe'],
    'name': ['sue', 'devon', 'carey', 'carey'],
    'series': ['111', '222', '333', '444'],
    'date': ['1/1/2023']*4
}
df = pd.DataFrame(data)

当前代码的问题

  1. 仅针对单个列column_name处理,未批量覆盖需要重复的多列(如type、name、series)
  2. 生成的重复列未设置自定义列名(如type1、type2),导致列名重复混乱
  3. 重复列被追加到DataFrame末尾,不符合"重复列紧跟原列"的顺序要求

解决方案一:遍历插入法(精准控制列位置)

通过遍历需要重复的列,在原列后逐个插入重复列,保证列顺序完全符合预期:

# 定义需要重复的列及其重复次数:key=原列名,value=重复次数
dup_config = {
    'type': 3,
    'name': 3,
    'series': 1
}

# 遍历每个需要重复的列
for col in dup_config:
    repeat_times = dup_config[col]
    # 获取原列在DataFrame中的位置索引
    original_col_idx = df.columns.get_loc(col)
    
    # 生成对应次数的重复列
    for i in range(1, repeat_times + 1):
        new_col_name = f"{col}{i}"
        # 在原列的下一个位置插入重复列,内容与原列完全一致
        df.insert(original_col_idx + i, new_col_name, df[col])

解决方案二:列序重构法(灵活适配复杂场景)

先构建目标列顺序列表,再基于原数据生成新的DataFrame,适合需要整体调整列顺序的场景:

# 定义需要重复的列及其重复次数
dup_config = {
    'type': 3,
    'name': 3,
    'series': 1
}

# 构建目标列顺序
target_columns = []
for col in df.columns:
    target_columns.append(col)
    # 如果当前列需要重复,追加对应的重复列名
    if col in dup_config:
        repeat_times = dup_config[col]
        target_columns.extend([f"{col}{i}" for i in range(1, repeat_times + 1)])

# 生成新的DataFrame
new_df = pd.DataFrame()
for col in target_columns:
    # 判断是否为原列,否则提取原列名获取数据
    if col in df.columns:
        new_df[col] = df[col]
    else:
        original_col = col[:-1]  # 从type1提取type
        new_df[col] = df[original_col]

# 替换原DataFrame
df = new_df

验证结果

执行上述任意方案后,输出df即可得到你期望的格式:

ID   type type1 type2 type3    name  name1  name2  name3 series series1        date
0  AA   all   all   all   all     sue    sue    sue    sue    111     111  1/1/2023
1  AA    ok    ok    ok    ok   devon  devon  devon  devon    222     222  1/1/2023
2  BB   yes   yes   yes   yes   carey  carey  carey  carey    333     333  1/1/2023
3  CC maybe maybe maybe maybe   carey  carey  carey  carey    444     444  1/1/2023

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:30:08