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

如何用另一DataFrame的行替换并扩展pandas DataFrame指定行?

实现方案

需求拆解

我们要完成的是:把df里option列标记为fill_A/fill_B的行,替换成look_up_df中对应option(A或B)的所有行,同时保留df原有的列(比如other_colA),并整合look_up_df的列(比如other_colB)。

具体实现代码

import pandas as pd

# 原始输入数据
df = pd.DataFrame({
    'option':['A', 'A', 'B', 'B', 'fill_A', 'fill_B'], 
    'items':['11111', '22222', '33333', '11111', '', ''], 
    'other_colA':['','', '','', '','' ]
})

look_up_df = pd.DataFrame({
    'option':['A','A','A','B', 'B','B'], 
    'items':['11111', '22222', '33333', '44444', '55555', '66666'],  
    'other_colB':['','', '','', '','' ]
})

# 1. 拆分原数据:保留不需要填充的行,单独提取需要填充的行
keep_rows = df[~df['option'].str.startswith('fill_')].copy()
fill_rows = df[df['option'].str.startswith('fill_')].copy()

# 2. 把fill_A/fill_B转换成对应的目标option(A/B),方便和lookup表匹配
fill_rows['target_option'] = fill_rows['option'].str.replace('fill_', '')

# 3. 按目标option合并lookup表,拿到对应所有行
filled_data = fill_rows.merge(look_up_df, left_on='target_option', right_on='option', how='left')

# 4. 整理列结构:保留原df的other_colA,替换成lookup表的option/items,加上lookup表的other_colB
filled_data = filled_data.rename(columns={'option_y': 'option', 'items_y': 'items'})
filled_data = filled_data[['option', 'items', 'other_colA', 'other_colB']]

# 5. 合并保留行和填充后的行,得到最终结果
final_df = pd.concat([keep_rows, filled_data], ignore_index=True)

# 查看结果
print(final_df)

代码说明

  • 先拆分数据:把原df里不需要替换的行单独拎出来,避免后续操作影响它们;
  • 处理填充标记:把fill_A这类标记转换成A,才能和lookup表的option列匹配;
  • 合并lookup表:通过匹配后的target_option,把lookup表中对应option的所有行都关联过来;
  • 整理列:确保最终结果的列和需求一致,保留原df的专属列,同时整合lookup表的列;
  • 拼接结果:把原本保留的行和填充后的行合并,得到完整的扩展结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:35:24