带有MultiIndex标签的Pandas DataFrame.update [英] Pandas DataFrame.update with MultiIndex label

查看:88
本文介绍了带有MultiIndex标签的Pandas DataFrame.update的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于具有MultiIndex的DataFrame A和具有一维索引的DataFrame B,如何使用B中的新值更新B的值,其中B的索引应与A的第二个索引标签匹配.

Given a DataFrame A with MultiIndex and a DataFrame B with one-dimensional index, how to update column values of A with new values from B where the index of B should be matched with the second index label of A.

测试数据:

begin = [10, 10, 12, 12, 14, 14]
end = [10, 11, 12, 13, 14, 15]
values = [1, 2, 3, 4, 5, 6]
values_updated = [10, 20, 3, 4, 50, 60]

multiindexed = pd.DataFrame({'begin': begin,
                             'end': end,
                             'value': values})
multiindexed.set_index(['begin', 'end'], inplace=True)

singleindexed = pd.DataFrame.from_dict(dict(zip([10, 11, 14, 15],
                                            [10, 20, 50, 60])),
                                   orient='index')
singleindexed.columns = ['value']

期望的结果应该是

               value
begin end       
10    10       10
      11       20
12    12       3
      13       4
14    14       50
      15       60

现在我正在考虑

multiindexed.update(singleindexed)

我搜索了DataFrame.update的文档,但找不到任何东西.索引处理.

I searched the docs of DataFrame.update, but could not find anything w.r.t. index handling.

我想念一种更简单的方法吗?

Am I missing an easier way to accomplish this?

推荐答案

您可以使用

You can use loc for selecting data in multiindexed and then set new values by values:

print singleindexed.index
Int64Index([10, 11, 14, 15], dtype='int64')

print singleindexed.values
[[10]
 [20]
 [50]
 [60]]

idx = pd.IndexSlice

print multiindexed.loc[idx[:, singleindexed.index],:]
           value
start end       
10    10       1
      11       2
14    14       5
      15       6

multiindexed.loc[idx[:, singleindexed.index],:] = singleindexed.values
print multiindexed
           value
start end       
10    10      10
      11      20
12    12       3
      13       4
14    14      50
      15      60

在文档中使用切片器.

这篇关于带有MultiIndex标签的Pandas DataFrame.update的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆