我正在创建一个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
最佳答案
如何使用union*将两个多索引连接在一起:
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更具可读性。
关于python - 来自两个索引唯一值乘积的MultiIndex,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25656365/