通过索引和列合并使用MultiIndex列合并/连接/附加两个Pandas DataFrame

时间:2013-12-20 11:31:45

标签: python pandas dataframe multi-index

我一直在我的桌子上撞到这个,无法弄清楚是否有办法,也许我正在尝试一些不可能的事情。

我有两个带有MultiIndex列(三个级别)和时间索引(单个级别)的DataFrame。第一个是这样的:

border           a-b                 c-d
from               a         b         c
to                 b         a         d
2009-03-01 -0.778346 -0.928997       NaN
2009-03-02 -1.352559  1.247335       NaN
2009-03-03 -0.967939  0.432638       NaN
2009-03-04  0.786094 -2.209559       NaN
2009-03-05 -0.001338  1.084152       NaN
2009-03-06  1.163334       NaN       NaN
2009-03-07 -0.587593       NaN       NaN
2009-03-08  0.118469       NaN       NaN
2009-03-09       NaN       NaN -1.272959
2009-03-10       NaN       NaN -1.207129
2009-03-11       NaN       NaN  0.244019

对于这个DF,我想添加以下内容:

border           a-b
from               a
to                 b
2009-03-09  1.243296
2009-03-10 -0.049870
2009-03-11  1.599999

考虑行和列索引。结果应该是:

border           a-b                 c-d
from               a         b         c
to                 b         a         d
2009-03-01 -0.778346 -0.928997       NaN
2009-03-02 -1.352559  1.247335       NaN
2009-03-03 -0.967939  0.432638       NaN
2009-03-04  0.786094 -2.209559       NaN
2009-03-05 -0.001338  1.084152       NaN
2009-03-06  1.163334       NaN       NaN
2009-03-07 -0.587593       NaN       NaN
2009-03-08  0.118469       NaN       NaN
2009-03-09  1.243296       NaN -1.272959
2009-03-10 -0.049870       NaN -1.207129
2009-03-11  1.599999       NaN  0.244019

我尝试了几种方法,包括使用Merge和Join,但无法使其正常工作。

任何想法?提前谢谢。

P.S。我可以发布用于生成上面两个DF的代码,如果有任何帮助,但它有点长。但无论如何我正在寻找一个通用的答案,列的确切名称或行的索引是无关紧要的(甚至可能是整数的索引)。

1 个答案:

答案 0 :(得分:6)

尝试pandas.DataFrame.update

DataFrame.update(other, join='left', overwrite=True,
                 filter_func=None, raise_conflict=False)
  

使用传递的DataFrame中的非NA值修改DataFrame。对齐指数