【发布时间】:2019-09-28 10:33:23
【问题描述】:
我有一个 3 级的嵌套字典,
example_d = {'attribute_001': {'colour': {'blue': 5, 'green': 5, 'red': 5},
'country': {'France': 3, 'Germany': 3, 'India': 3, 'UK': 3, 'USA': 3}},
'attribute_002': {'colour': {'blue': 5, 'green': 5, 'red': 5},
'country': {'France': 3, 'Germany': 3, 'India': 3, 'UK': 3, 'USA': 3}},
'attribute_003': {'colour': {'blue': 5, 'green': 5, 'red': 5},
'country': {'France': 3, 'Germany': 3, 'India': 3, 'UK': 3, 'USA': 3}},
'attribute_004': {'colour': {'blue': 5, 'green': 5, 'red': 5},
'country': {'France': 3, 'Germany': 3, 'India': 3, 'UK': 3, 'USA': 3}},
'attribute_005': {'colour': {'blue': 5, 'green': 5, 'red': 5},
'country': {'France': 3, 'Germany': 3, 'India': 3, 'UK': 3, 'USA': 3}}}
我想将它移动到 pandas 数据框中,以便行索引来自我的字典的第一级,并将剩余的级别用作分层列索引。
我可以通过使用以下内容来接近,改编here的答案:
pd.concat({key:pd.DataFrame.from_dict(example_d[key],orient='columns')
for key in example_d.keys()}).unstack(1)
这给了我:
但我需要最低级别的多级列索引来尊重他们的父母。
即在colour 标题下,我只想显示颜色列,在country 标题下,我只想看到国家/地区列。
【问题讨论】:
标签: python pandas multi-index