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

如何批量更新Pandas DataFrame中匹配Symbol的多行SecurityID值

批量更新DataFrame中相同Symbol对应的SecurityID

问题说明

有两个DataFrame:DF1包含多行重复Symbol(如示例中的UGE),对应SecurityID均为NaN;DF2存储了该Symbol对应的有效SecurityID值。使用df1.update(df2)仅能更新首个匹配行,需要无循环批量更新所有相同Symbol的行。

示例数据集

DF1:

Symbol  SecurityID
3856     UGE         NaN
13583    UGE         NaN  
25422    UGE         NaN 
36046    UGE         NaN 
47362    UGE         NaN  
58434    UGE         NaN

DF2:

Symbol  SecurityID
3856    UGE    128901

当前无效输出

执行df1.update(df2)后的结果:

Symbol  SecurityID
3856     UGE         128901
13583    UGE         NaN  
25422    UGE         NaN 
36046    UGE         NaN 
47362    UGE         NaN  
58434    UGE         NaN

解决方案

方法1:构建映射字典批量替换

先从DF2生成Symbol到SecurityID的映射,再用map批量更新DF1:

# 生成Symbol与SecurityID的映射字典
id_mapping = df2.set_index('Symbol')['SecurityID'].to_dict()
# 批量更新DF1的SecurityID列
df1['SecurityID'] = df1['Symbol'].map(id_mapping)

方法2:通过merge关联更新

按Symbol左连接两个DataFrame,提取新值替换原列:

# 按Symbol左连接,保留DF1所有行,区分重复列名
merged = df1.merge(df2[['Symbol', 'SecurityID']], on='Symbol', how='left', suffixes=('', '_new'))
# 用新值覆盖原SecurityID
df1['SecurityID'] = merged['SecurityID_new']

方法3:直接替换特定Symbol的NaN值

针对目标Symbol的NaN值批量替换:

import numpy as np
# 获取DF2中UGE对应的SecurityID值
target_id = df2.loc[df2['Symbol'] == 'UGE', 'SecurityID'].iloc[0]
# 替换DF1中所有UGE行的NaN值
df1.loc[df1['Symbol'] == 'UGE', 'SecurityID'] = target_id

预期结果

执行上述任一方法后,DF1所有Symbol为UGE的行SecurityID都会被更新为128901:

Symbol  SecurityID
3856     UGE      128901
13583    UGE      128901  
25422    UGE      128901 
36046    UGE      128901 
47362    UGE      128901  
58434    UGE      128901

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:16