9

我一直在用头撞我的桌子,不知道是否有办法,也许我正在尝试一些不可能的事情。

我有两个带有 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,但无法使其正常工作。

有任何想法吗?提前致谢。

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

4

1 回答 1

6

试试pandas.DataFrame.update

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

使用传递的 DataFrame 中的非 NA 值修改 DataFrame。对齐索引

于 2013-12-20T11:37:52.743 回答