【问题标题】:Creating Multiindex Panda Dataframe from nested dict从嵌套字典创建多索引熊猫数据框
【发布时间】:2021-02-04 09:30:17
【问题描述】:

我有一个这样的目录:

dict = {'Filter1':{'Method1':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}},
                   'Method2':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}}},
        'Filter2':{'Method1':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}},
                   'Method2':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}}}}

我想创建一个这种形状的数据框:

                      Filter1         Filter2
                Method1   Method2   Method1  Method2
Function1 Value1   1        1          1         1
          Value2   2        2          2         2
Function2 Value1   1        1          1         1
          Value2   2        2          2         2

我该怎么做?我能找到的所有帖子都只是指两个子行或子列,但从来没有两个。 谢谢各位!!

到目前为止,我尝试了这种方法:

df = pd.DataFrame.from_dict({(i, j): dict[i][j]
                         for i in dict.keys()
                         for j in dict[i].keys()
                         },
                        orient='index')

女巫给了我这个结果:

                                       Fuction1                    Fuction2
Filter1 Method1  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
        Method2  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
Filter2 Method1  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
        Method2  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}

但我希望交换行和列并将 Value1 和 Value2 作为行名

【问题讨论】:

  • {'Value1': 1, 'Value2': 2, 'Value2'} 这不是有效的python。
  • 你是对的。是复制粘贴错误。
  • 不。这只会创建很多子列而不是子行

标签: python pandas dataframe dictionary nested


【解决方案1】:

您希望 1) 展平您的字典,2) 将其加载到数据框中,以及 3) 根据自己的喜好重新格式化数据框。

# 1. Flatten, eg using https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys
import collections
def flatten(dictionary, parent_key=False, separator='.'):
    """
    Turn a nested dictionary into a flattened dictionary
    :param dictionary: The dictionary to flatten
    :param parent_key: The string to prepend to dictionary's keys
    :param separator: The string used to separate flattened keys
    :return: A flattened dictionary
    """

    items = []
    for key, value in dictionary.items():
        new_key = str(parent_key) + separator + key if parent_key else key
        if isinstance(value, collections.MutableMapping):
            items.extend(flatten(value, new_key, separator).items())
        elif isinstance(value, list):
            for k, v in enumerate(value):
                items.extend(flatten({str(k): v}, new_key).items())
        else:
            items.append((new_key, value))
    return dict(items)

data_flat = flatten(data_dict)

# 2. Load it in pandas
df = pd.DataFrame.from_dict(data_flat, orient="index")

# 3. Reshape to your liking
df.index = pd.MultiIndex.from_tuples(df.index.str.split(".").map(tuple))
df = df.unstack(level=[0,1]).droplevel(axis=1, level=0) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多