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

基于指定条件更新Pandas DataFrame中的列数据

Pandas DataFrame 条件关联更新实现

需求说明

现有主 DataFrame 如下:

IDcountrymoneycodemoney_addother
832932OtherNaN00000NaNNaN
217#8#NaNNaNNaNNaNNaN
1329T2France12131000203452123
124932FranceNaN00016NaNNaN
194022FranceNaN00000NaNNaN

另有一张关联表:

cod_tmoneymoney_addother
00000453272323321
00016121323822843
0001813138393183
00020181327328128
0003089323204829

需实现:当主表中 code 列不为空且 money 列为空时,以主表的code列和关联表的cod_t列为关联键,将关联表的money、money_add、other值更新到主表对应行。

更新后的预期结果:

IDcountrymoneycodemoney_addother
832932Other45320000072323321
217#8#NaNNaNNaNNaNNaN
1329T2France12131000203452123
124932France12130001623822843
194022France45320000072323321

实现代码

通过merge结合条件筛选完成更新,代码如下:

import pandas as pd

# 构造主表
main_df = pd.DataFrame({
    'ID': ['832932', '217#8#', '1329T2', '124932', '194022'],
    'country': ['Other', None, 'France', 'France', 'France'],
    'money': [None, None, 12131, None, None],
    'code': ['00000', None, '00020', '00016', '00000'],
    'money_add': [None, None, 3452, None, None],
    'other': [None, None, 123, None, None]
})

# 构造关联表
lookup_df = pd.DataFrame({
    'cod_t': ['00000', '00016', '00018', '00020', '00030'],
    'money': [4532, 1213, 1313, 1813, 8932],
    'money_add': [72323, 23822, 8393, 27328, 3204],
    'other': [321, 843, 183, 128, 829]
})

# 筛选需要更新的行
mask = main_df['code'].notna() & main_df['money'].isna()

# 关联获取更新值
updated_part = main_df[mask].merge(
    lookup_df,
    left_on='code',
    right_on='cod_t',
    how='left',
    suffixes=('', '_new')
)

# 更新目标列
updated_part['money'] = updated_part['money_new']
updated_part['money_add'] = updated_part['money_add_new']
updated_part['other'] = updated_part['other_new']

# 保留原表列结构
updated_part = updated_part[main_df.columns]

# 合并更新部分与未更新部分,恢复原顺序
final_df = pd.concat([main_df[~mask], updated_part]).sort_index()

print(final_df)

运行代码后即可得到预期的更新结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:43:29