Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultiIndex from product of unique values of two indexes

I am creating a MultiIndex.from_product(), but it must be the product of the unique values from two separate MultiIndexes. My solution below works, but I wonder 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())

The desired result:

country  region
AU       East  
         North 
         South 
         West  
UK       East  
         North 
         South 
         West  
US       East  
         North 
         South 
         West  
like image 880
dmvianna Avatar asked Dec 04 '25 20:12

dmvianna


1 Answers

How's about using union* to join the 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]])

as desired.

*Initial answer was to use append, but I think union is more readable.

like image 158
Andy Hayden Avatar answered Dec 07 '25 17:12

Andy Hayden