python - 合并数据框
问题描述
我正在尝试合并这两个数据框:
df1=
pais ano cantidad
0 Chile 2000 10
1 Chile 2001 11
2 Chile 2002 12
df2=
pais ano cantidad
0 Chile 1999 0
1 Chile 2000 0
2 Chile 2001 0
3 Chile 2002 0
4 Chile 2003 0
我正在尝试将 df1 合并到 df2 中,并将现有的 año 行替换为 df1 中的行。这是我现在正在尝试的代码以及我得到的代码:
df=df1.combine_first(df2)
df=
pais ano cantidad
0 Chile 2000.0 10.0
1 Chile 2001.0 11.0
2 Chile 2002.0 12.0
3 Chile 2002.0 0.0
4 Chile 2003.0 0.0
如您所见,缺少对应于 1999 的行,并且 2002 的 'cantidad'= 0 的行不应该存在。我想要的输出是这样的:
df=
pais ano cantidad
0 Chile 1999 0
1 Chile 2000 10
2 Chile 2001 11
3 Chile 2002 12
4 Chile 2003 0
有任何想法吗?谢谢!
解决方案
将how='outer
参数添加到合并中。
默认情况下,merge
与“inner”一起使用,这意味着它只需要两个数据框(交集)中的值,而您想要这些部分的联合。
此外,您可能需要添加on="ano"
以声明要合并的列。您的情况可能不需要它,但值得一试。
请查看Pandas Merging 101了解更多详情
推荐阅读
- php - 一个请求中带有 json 的 CakePHP REST API 多部分文件
- php - 将照片上传到服务器时,将文件上传到服务器未定义索引时出错
- javascript - Joomla!正在强制我的 concat 加 '+' 到 "%20"
- android - Android 库不适用于 Lib GDX 制作的项目
- flask - SQLAlchemy 不允许我在测试夹具中多次设置 Flask 应用程序
- macos - macOS en5 网络无法关闭
- reactjs - Apollo 客户端和更新表单
- php - Etsy PHP Oauth:无法获取访问令牌
- java - 在春季数据中使用什么代替 fetch.EAGER?
- html - 在 Bootstrap 中向面板标题添加特色角