【问题标题】:Left merge using pandas on 2 csv files在 2 个 csv 文件上使用 pandas 进行左合并
【发布时间】:2023-03-23 04:47:01
【问题描述】:

我有 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

【问题讨论】:

  • 请将您的数据粘贴为表格/代码,而不是屏幕截图。在阅读您的 csv 后,还要检查 table1.columnstable2.columns。您的列名可能有前导/尾随空格,并且不完全是“名称”
  • @not_speshal 感谢您的快速回复。如您所想,这是名称的问题。但是,我遇到了更新问题中指定的另一个问题。

标签: python pandas csv


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助。您的解决方案非常接近,我已经更新了我的问题。即第一个 NaN 变为 900,第二个 NaN 变为 32。
  • @danielstafford - 查看编辑。你可以使用combine_first
猜你喜欢
  • 2013-12-02
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2017-08-08
  • 2016-05-01
  • 2018-06-11
  • 1970-01-01
相关资源
最近更新 更多