我正在创建一个MultiIndex.from_产品(),但它必须是来自两个独立多重索引的唯一值的乘积。我下面的解决方案是可行的,但我想知道是否有更优雅的解决方案。在
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())
预期结果:
^{pr2}$
如何使用union*将两个多重索引连接在一起:
此级别是您要传递给
^{pr2}$from_product
:如你所愿。在
最初的答案是使用append,但我认为union更具可读性。
相关问题 更多 >
编程相关推荐