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

如何用Python在Excel同一行新增列并添加对应数据?

解决方案

方法1:在现有循环中直接赋值

先初始化新列避免报错,然后通过行索引将处理后的数据写入对应位置:

df = pd.read_excel(input_file)
# 提前创建空列,防止赋值时出现KeyError
df['Test1'] = ''
df['Test2'] = ''

for index, row in df.iterrows():
    value = row["Test"]
    matching_rows = some_operation(input_file, column_name, value)     
    ab = matching_rows["Test1"]
    abc = matching_rows['Test2']
    
    # 若ab/abc是列表或Series,先转为字符串(可按需调整分隔符);单个值直接赋值
    df.loc[index, 'Test1'] = ', '.join(ab) if isinstance(ab, (list, pd.Series)) else ab
    df.loc[index, 'Test2'] = ', '.join(abc) if isinstance(abc, (list, pd.Series)) else abc

# 保存处理后的结果到Excel
df.to_excel('output_file.xlsx', index=False)

方法2:用apply替代循环(更高效)

Pandas的apply比iterrows性能更优,适合批量行处理:

df = pd.read_excel(input_file)

def process_single_row(row):
    value = row["Test"]
    matching_rows = some_operation(input_file, column_name, value)
    ab = matching_rows["Test1"]
    abc = matching_rows['Test2']
    
    # 整理Test1和Test2的输出格式
    test1_val = ', '.join(ab) if isinstance(ab, (list, pd.Series)) else ab
    test2_val = ', '.join(abc) if isinstance(abc, (list, pd.Series)) else abc
    return pd.Series([test1_val, test2_val], index=['Test1', 'Test2'])

# 将处理结果合并到原DataFrame
df[['Test1', 'Test2']] = df.apply(process_single_row, axis=1)

# 保存最终结果
df.to_excel('output_file.xlsx', index=False)

注意事项

  • 如果matching_rows["Test1"]返回的是单个值而非集合,直接赋值即可,无需join操作。
  • 必须执行to_excel步骤,否则修改仅停留在内存中,不会写入文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:22:37