python - 在 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
解决方案
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
推荐阅读
- visual-studio - TFS 在 Visual Studio for Mac 中是否可用
- java - Spring Boot 可能只存在一个 AsyncConfigurer
- oracle - 在 teradta 中去除双引号
- sql - 正则表达式不匹配正确的字符串
- swift - 图像缓存——如何控制图像何时被处理?
- ajax - 带有回调的 Yahoo.util.connect.asyncRequest POST 突然停止工作
- php - Laravel 结合 OR AND 解决方案
- sql - Oracle sql 获取用户在 MONDAY 字段中的值 IF TODAY 是 MONDAY
- ajax - Set-Cookie(来自 AJAX)标头未在浏览器中设置 cookie
- java - 元素此时不可点击 - 其他元素将收到点击