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

如何基于匹配的Name字段用CSV2的数值更新CSV1的Price字段

问题解决:Pandas匹配Name字段更新Price值

你当前代码的问题是左连接后直接使用table2的Price列作为最终Price,未匹配到Name的行没有保留table1原本的Price值,所以出现NaN。
以下是两种可行的修改方案:


方案1:merge后填充空值

合并时保留两个表的Price列,用table2的新价格覆盖,空值用table1的原有价格填充:

import pandas as pd

table1 = pd.read_csv('path/table1.csv', index_col=0)
table2 = pd.read_csv('path/table2.csv', index_col=0)

# 合并时用后缀区分两个表的Price列,注意如果字段名带空格要对应写为"Name "
merged = table1.merge(table2[['Name', 'Price']], on='Name', how='left', suffixes=('_old', '_new'))
# 新Price有值就用新值,为空就保留原Price
merged['Price'] = merged['Price_new'].fillna(merged['Price_old'])
# 提取需要的列得到最终表
new_table = merged[['Name', 'ATT1', 'ATT2', 'Price']]

print(new_table)

方案2:使用update方法(更简洁)

直接通过索引匹配更新,不需要手动处理空值,代码更精简:

import pandas as pd

table1 = pd.read_csv('path/table1.csv', index_col=0)
table2 = pd.read_csv('path/table2.csv', index_col=0)

# 将Name设为索引用于匹配,注意如果字段名带空格要对应写为"Name "
table1 = table1.set_index('Name')
table2 = table2.set_index('Name')

# 仅更新匹配到的Name对应的Price值,未匹配的自动保留原值
table1.update(table2['Price'])

# 重置索引并调整列顺序
new_table = table1.reset_index()[['Name', 'ATT1', 'ATT2', 'Price']]

print(new_table)

两种方案执行后都可以得到你需要的预期结果,注意如果你的CSV字段名实际是带末尾空格的Name ,请将代码中所有Name替换为Name ,保证字段匹配一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:36:03