首页 > 解决方案 > 在 2 个 csv 文件上使用 pandas 进行左合并

问题描述

我有 2 个 csv 表:

我正在尝试找到一种将 table2 合并到 table1 的方法。只要 table1 和 table2 具有相同的 Name 值,则将 table1 中的相应价格替换为 table2 中找到的价格,否则将 table1 保持原样。

当前代码:

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

new_table = table1[["Name ", "ATT1", "ATT2"]].merge(table2[["Price", "Name "]], on="Name ", how="left")
print(new_table)

但是,这会导致以下结果:

   Price  Name   ATT1  ATT2
0     12   APPL    69    81
1    900  GOOGL   303   392
2     32    INV    39     9
   Price     Name 
0   1231      APPL
1     39  FACEBOOK
   Name   ATT1  ATT2   Price
0   APPL    69    81  1231.0
1  GOOGL   303   392     NaN
2    INV    39     9     NaN

我想要 new_table 打印的是:

   Name   ATT1  ATT2   Price
0   APPL    69    81  1231.0
1  GOOGL   303   392     900
2    INV    39     9     32

标签: pythonpandascsv

解决方案


drop合并前 table1 中的“价格”列:

new_table = table1.drop("Price", axis=1).merge(table2, on="Name", how="left")

>>> new_table
    Name  ATT1  ATT2   Price
0   APPL    69    81  1231.0
1  GOOGL   303   392     NaN
2    INV    39     9     NaN

顺便说一句,两个表中的“未命名:0”列可能是由于 csv 文件中的索引列未命名。index_col=0你可以通过像这样传递来避免这种pd.read_csv情况:

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

或者,仅使用您需要的列merge

new_table = table1[["Name", "ATT1", "ATT2"]].merge(table2[["Price", "Name"]], on="Name", how="left")
new_table["Price"] = new_table["Price"].combine_first(table1["Price"])

>>> new_table
    Name  ATT1  ATT2   Price
0   APPL    69    81  1231.0
1  GOOGL   303   392   900.0
2    INV    39     9    32.0

推荐阅读