从两个索引的唯一值的乘积创建MultiIndex

3 投票
1 回答
1633 浏览
提问于 2025-04-19 17:43

我正在使用 MultiIndex.from_product() 来创建一个多重索引,但这个索引必须是来自两个不同多重索引的唯一值的组合。我下面的解决方案可以实现这个目标,但我在想是否有更优雅的解决办法。

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 个回答

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看起来更清晰。

撰写回答