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

Python Pandas为Excel多表结构批量添加行的错误修正求助

问题描述

我是Python新手,正在编写代码自动化给包含多表结构的Excel工作表添加带值的行。该Excel的列包含Entity name、Entity ID、table column name、column type、type mode等字段,我需要为每个表添加新的表列。

我尝试提取唯一的表名(Entity name)和表ID(Entity ID)来为新表列创建行,但测试打印新行时,所有唯一的Entity name和Entity ID都被放在同一个单元格中。我需要为每个匹配对应表信息的值创建单独的行,以下是我的代码:

import pandas as pd

df = pd.read_excel('date_test.xlsx')

entity_id = pd.unique(df['Entity ID'])
entity_name = pd.unique(df['Entity name'])
activated = 'TRUE'
type1 = 'bool'
type2 = 'date'
type_mode = 'Required'

new_row = []

for i in entity_id:
    new_row = { 'Business Name' : ['is_active'],
                'Entity ID' : entity_id,
                'Entity name' : entity_name,
                'Activated' : activated,
                'Type' : type1,
                'Type mode' : type_mode}

    print(new_row) 

当前打印结果如下:

{'Business Name': ['is_active'], 
  'Entity ID': array(['680293be', 'a7e61af3', '9653d173',  'e96f789e', 'ab35ff16', '5b01ff4a', '56c759d3', '85d95d42', '3b2s878s'], dtype=object),
  'Entity name': array(['date_period_map_dim', 'calendar_year_dim', 'market_year_dim', 'fiscal_year_dim', 'month_dim', 'period_dim', 'period_type_dim', 'shipping_scheduling_calendar_dim', 'date_dim'], dtype=object), 
  'Activated': 'TRUE', 'Type': 'bool', 'Type mode': 'Required'}

我也曾将其改为列表格式,但仅改变了输出样式,不知该如何修正此问题?

解决方案

问题根源

  1. 循环中直接将整个entity_id和entity_name数组赋值给字典键,导致每个新行都包含所有实体的ID和名称,而非单个实体信息。
  2. 单独调用pd.unique()分别获取ID和名称,可能破坏两者的配对关系(比如顺序错位),导致新行的ID和名称不匹配。

修正代码

通过保留Entity ID和Entity name的配对关系,遍历每个唯一实体生成单独新行:

import pandas as pd

df = pd.read_excel('date_test.xlsx')

# 获取配对的唯一实体信息,确保ID和名称一一对应
unique_entities = df[['Entity ID', 'Entity name']].drop_duplicates().reset_index(drop=True)

activated = 'TRUE'
type1 = 'bool'
type_mode = 'Required'

new_rows = []

# 遍历每个唯一实体,生成单独的新行
for _, entity in unique_entities.iterrows():
    new_row = {
        'Business Name': 'is_active',  # 单个值即可,无需用列表
        'Entity ID': entity['Entity ID'],
        'Entity name': entity['Entity name'],
        'Activated': activated,
        'Type': type1,
        'Type mode': type_mode
    }
    new_rows.append(new_row)
    print(new_row)

# 可选:将新行合并到原表格并保存
new_df = pd.DataFrame(new_rows)
final_df = pd.concat([df, new_df], ignore_index=True)
final_df.to_excel('updated_date_test.xlsx', index=False)

关键说明

  • 使用df[['Entity ID', 'Entity name']].drop_duplicates()获取唯一的实体配对,避免ID和名称错位。
  • 循环时通过iterrows()遍历每个唯一实体,为每个实体生成独立的新行字典,确保每行只包含单个实体的信息。
  • 如果需要添加多种类型的新列(比如你提到的type2 = 'date'),可以复制循环块或在循环内添加逻辑生成不同行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:17:03