熊猫MultiIndex(超过2个级别)DataFrame到嵌套Dict / JSON

tgo*_*n18 5 python dictionary multi-index pandas

这个问题与类似,但我想进一步。是否可以将解决方案扩展到更多级别?多级数据框的.to_dict()方法有一些有希望的选择,但是大多数方法将返回由元组(即(A, 0, 0): 274.0)索引的条目,而不是将其嵌套在字典中。

有关我要完成的工作的示例,请考虑以下多索引数据框:

data = {0: {
        ('A', 0, 0): 274.0, 
        ('A', 0, 1): 19.0, 
        ('A', 1, 0): 67.0, 
        ('A', 1, 1): 12.0, 
        ('B', 0, 0): 83.0, 
        ('B', 0, 1): 45.0
    },
    1: {
        ('A', 0, 0): 254.0, 
        ('A', 0, 1): 11.0, 
        ('A', 1, 0): 58.0, 
        ('A', 1, 1): 11.0, 
        ('B', 0, 0): 76.0, 
        ('B', 0, 1): 56.0
    }   
}
df = pd.DataFrame(data).T
df.index = ['entry1', 'entry2']
df
# output:

         A                              B
         0              1               0
         0      1       0       1       0       1
entry1   274.0  19.0    67.0    12.0    83.0    45.0
entry2   254.0  11.0    58.0    11.0    76.0    56.0
Run Code Online (Sandbox Code Playgroud)

您可以想象我们这里有很多记录,而不仅仅是两个,而且索引名称可以是更长的字符串。您如何将其转换为如下所示的嵌套字典(或直接转换为JSON):

[
 {'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}},
  'B': {0: {0: 83.0, 1: 45.0}}},
 'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}},
  'B': {0: {0: 76.0, 1: 56.0}}}}
]
Run Code Online (Sandbox Code Playgroud)

我认为一定程度的递归可能会有所帮助,也许像这样,但到目前为止还没有成功。

Bra*_*mon 6

因此,您确实需要在这里做两件事:

  • df.to_dict()
  • 将此转换为嵌套字典。

df.to_dict(orient='index')给您一本以索引为键的字典;它看起来像这样:

>>> df.to_dict(orient='index')
{'entry1': {('A', 0, 0): 274.0,
  ('A', 0, 1): 19.0,
  ('A', 1, 0): 67.0,
  ('A', 1, 1): 12.0,
  ('B', 0, 0): 83.0,
  ('B', 0, 1): 45.0},
 'entry2': {('A', 0, 0): 254.0,
  ('A', 0, 1): 11.0,
  ('A', 1, 0): 58.0,
  ('A', 1, 1): 11.0,
  ('B', 0, 0): 76.0,
  ('B', 0, 1): 56.0}}
Run Code Online (Sandbox Code Playgroud)

现在您需要嵌套它。这是Martijn Pieters的一个技巧:

def nest(d: dict) -> dict:
    result = {}
    for key, value in d.items():
        target = result
        for k in key[:-1]:  # traverse all keys but the last
            target = target.setdefault(k, {})
        target[key[-1]] = value
    return result
Run Code Online (Sandbox Code Playgroud)

全部放在一起:

def df_to_nested_dict(df: pd.DataFrame) -> dict:
    d = df.to_dict(orient='index')
    return {k: nest(v) for k, v in d.items()}
Run Code Online (Sandbox Code Playgroud)

输出:

>>> df_to_nested_dict(df)
{'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}},
  'B': {0: {0: 83.0, 1: 45.0}}},
 'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}},
  'B': {0: {0: 76.0, 1: 56.0}}}}
Run Code Online (Sandbox Code Playgroud)

  • 对于使用类型提示,您将获得+1 :) (2认同)