python - Pandas 完整外部索引与 NaN 连接以处理不匹配的索引

标签 python pandas join merge

尝试对这两个 Pandas 数据帧进行完整的外部联接:

df1 = pd.DataFrame({'a': [1,2,1], 'b': [1,1,2], 'c': [1,2,3]}).set_index(['a', 'b'])
df2 = pd.DataFrame({'a': [1,2,3], 'd': [11,12,13]}).set_index(['a'])

>>> df1
     c
a b   
1 1  1
2 1  2
1 2  3

>>> df2
    d
a    
1  11
2  12
3  13

我继续像这样合并这两个:

>>> df1.merge(df2, how='outer', left_index=True, right_index=True)

     c   d
a b       
1 1  1  11
2 1  2  12
1 2  3  11

虽然我希望在此连接中也应返回不匹配的索引,如下所示:

       c    d
a b       
1 1    1    11
2 1    2    12
3 NaN  NaN  13
1 2    4    11

最佳答案

你可以使用一个小技巧 - reset_index按级别b合并和最后set_index通过b:

df2 = df1.reset_index(level='b')
         .merge(df2, how='outer', left_index=True, right_index=True)
         .set_index('b', append=True)
print (df2)
         c   d
a b           
1 1.0  1.0  11
  2.0  3.0  11
2 1.0  2.0  12
3 NaN  NaN  13

关于python - Pandas 完整外部索引与 NaN 连接以处理不匹配的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206026/

相关文章:

python - 如何在 Python 中评估 xe^x/(e^x-1) 的数值稳定性?

python - Singledispatch 装饰器并不像宣传的那样工作

python - 如何将行添加到数据框中以组织时间序列

python - 按时间窗口分组的 Pandas

python - 使用 python/opencv pandas 在集合中查找规范图像

PHP MYSQL Join 并输出不匹配的结果

用于列表的 Python gcd

python - 从文本文件的一行中分割两个范围

python - 连接两个 DataFrame 并替换 Python 中的列值

mysql - 对 JOIN 感到困惑 - 结果中数据丢失