使用pandas对两个CSV文件左合并 匹配Name列更新Price列的问题
问题根因
你当前使用左连接合并时仅保留了table2的Price字段,匹配不到的对应位置会生成NaN,没有保留table1中原本的Price数值,所以和预期结果不符。
解决方案
方案1:合并后填充空值
合并时区分两个表的Price字段,用table1的旧Price填充table2没匹配到的空值:
import pandas as pd table1 = pd.read_csv('path/table1.csv', index_col=0) table2 = pd.read_csv('path/table2.csv', index_col=0) # 合并时给同名字段加后缀区分 new_table = table1.merge(table2[["Name ", "Price"]], on="Name ", how="left", suffixes=("_old", "_new")) # 优先用table2的Price,空值用table1的Price填充 new_table["Price"] = new_table["Price_new"].fillna(new_table["Price_old"]) # 筛选出需要的字段 new_table = new_table[["Name ", "ATT1", "ATT2", "Price"]] print(new_table)
方案2:索引更新(更简洁)
把Name作为索引,直接用table2的Price字段覆盖更新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) # 将Name设为索引后更新 table1 = table1.set_index('Name ') table2 = table2.set_index('Name ') table1.update(table2['Price']) # 重置索引得到最终结果 new_table = table1.reset_index() print(new_table)
两种方案运行后都可以得到你预期的输出结果。
内容的提问来源于stack exchange,提问作者daniel stafford
相关产品推荐
相关产品推荐

