MultiIndex from the product of unique values ​​of two indices

I am creating MultiIndex.from_product (), but it must be the product of unique values ​​from two separate MultiIndexes. My solution below works, but I'm wondering if there is a more elegant solution.

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())

      

Desired output:

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

      

+3


source to share


1 answer


How about using union * to combine two MultiIndex together:

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)

      

The levels of this are what you want to pass to 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]])

      

optional.

* The original answer was to use append, but I think the join is more readable.

+1


source







All Articles