MultiIndex来自两个索引的唯一值的乘积

时间:2014-09-04 02:19:51

标签: python pandas multi-index

我正在创建一个MultiIndex.from_product(),但它必须是来自两个独立MultiIndex的唯一值的乘积。我的解决方案有效,但我想知道是否有更优雅的解决方案。

from pandas import MultiIndex
from collections import OrderedDict

countries = array(['US', 'UK', 'AU'], dtype=object)
regions = array(['North', 'South'], dtype=object)
index_names = ['country','region']
index = MultiIndex.from_product([countries, regions], names=index_names)

dic = OrderedDict()
for name in index.names:
    dic[name] = index.get_level_values(name).unique()

countries_2 = array(['US'], dtype=object)
regions_2 = array(['South','East','West'], dtype=object)
index_names_2 = ['country','region']
index_2 = MultiIndex.from_product([countries_2, regions_2], names=index_names_2)

dic_union = OrderedDict()
for key in dic.keys():
    dic_union[key] = unique(concatenate([index_2.get_level_values(key).unique(),
                                 dic[key]]))
print MultiIndex.from_product(dic_union.values(), names=dic_union.keys())

期望的结果:

country  region
AU       East  
         North 
         South 
         West  
UK       East  
         North 
         South 
         West  
US       East  
         North 
         South 
         West  

1 个答案:

答案 0 :(得分:1)

如何使用union *将两个MultiIndex连接在一起:

In [11]: index.union(index_2)
Out[11]:
MultiIndex(levels=[[u'AU', u'UK', u'US'], [u'East', u'North', u'South', u'West']],
           labels=[[0, 0, 1, 1, 2, 2, 2, 2], [1, 2, 1, 2, 0, 1, 2, 3]],
           names=[u'country', u'region'],
           sortorder=0)

这是您要传递给from_product的级别:

In [12]: index.union(index_2).levels
Out[12]: FrozenList([[u'AU', u'UK', u'US'], [u'East', u'North', u'South', u'West']])

In [13]: pd.MultiIndex.from_product(index.union(index_2).levels)
Out[13]:
MultiIndex(levels=[[u'AU', u'UK', u'US'], [u'East', u'North', u'South', u'West']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]])

根据需要。

*最初的答案是使用append,但我认为union更具可读性。