首页 > 解决方案 > 合并数据框

问题描述

我正在尝试合并这两个数据框:

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

有任何想法吗?谢谢!

标签: pythonpandasdataframemerge

解决方案


how='outer参数添加到合并中。

默认情况下,merge与“inner”一起使用,这意味着它只需要两个数据框(交集)中的值,而您想要这些部分的联合。

此外,您可能需要添加on="ano"以声明要合并的列。您的情况可能不需要它,但值得一试。

请查看Pandas Merging 101了解更多详情


推荐阅读